You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2020/09/15 16:42:14 UTC

[GitHub] [airflow] ashb opened a new pull request #10956: Officially support running more than one scheduler concurrently.

ashb opened a new pull request #10956:
URL: https://github.com/apache/airflow/pull/10956


   Depends upon #10949, ignore first commit when reviewing please.
   
   Here it is. The "big" one. Smaller than I thought, but still a very fundamental change!
   
   This PR is still in draft -- there are one or two TODOs left in the code that will need to be fixed before final merge, and while they are import, there is still enough here to start reviewing.
   
   - [ ] Test that my forward-port of the changes actually works again. (I wanted to get the code up for review, so there may be some transcription errors breaking things.)
   - [ ] DAG SLAs need to happen via the parsing process
   - [ ] Adding back dagrun_timeout support
   - [ ] dag_run.verify_integrity is slow, and we don't want to call it every time, just when the dag structure changes (which we can know now thanks to DAG Serialization)
   - [ ] Add a savepoint in verify_integrity (to avoid rollback killing the whole transaction and releasing the locks. 
   - [ ] Produce benchmark figures against this branch, not a 4 month old version of master branch.
   
   This PR implements scheduler HA as proposed in AIP-15. The high level design is as follows:
   
   - Move all scheduling decisions into SchedulerJob (requiring DAG serialization in the scheduler)
   - Use row-level locks to ensure schedulers don't stomp on each other
     (`SELECT ... FOR UPDATE`)
   - Use `SKIP LOCKED` for better performance when multiple schedulers are
     running. (Mysql < 8 and MariaDB don't support this)
   - Scheduling decisions are not tied to the parsing speed, but can
     operate just on the database
   
   **DagFileProcessorProcess**:
   
   Previously this component was responsible for more than just parsing the
   DAG files as it's name might imply. It also was responsible for creating
   DagRuns, and also making scheduling decisions of TIs, sending them from
   "None" to "scheduled" state.
   
   This commit changes it so that the DagFileProcessorProcess now will
   update the SerializedDAG row for this DAG, and make no scheduling
   decisions itself.
   
   To make the scheduler's job easier (so that it can make as many
   decisions as possible without having to load the possibly-large
   SerializedDAG row) we store/update some columns on the DagModel table:
   
   - `next_dagrun`: The execution_date of the next dag run that should be created (or
     None)
   - `next_dagrun_create_after`: The earliest point at which the next dag
     run can be created
   
   Pre-computing these values (and updating them every time the DAG is
   parsed) reduce the overall load on the DB as many decisions can be taken
   by selecting just these two columns/the small DagModel row.
   
   In case of max_active_runs, or `@once` these columns will be set to
   null, meaning "don't create any dag runs"
   
   **SchedulerJob**
   
   The SchedulerJob used to only queue/send tasks to the executor after
   they were parsed, and returned from the DagFileProcessorProcess.
   
   This PR breaks the link between parsing and enqueuing of tasks, instead
   of looking at DAGs as they are parsed, we now:
   
   -  store a new datetime column, `last_scheduling_decision` on DagRun
     table, signifying when a scheduler last examined a DagRun
   - Each time around the loop the scheduler will get (and lock) the next
     _n_ DagRuns via `DagRun.next_dagruns_to_examine`, prioritising DagRuns
     which haven't been touched by a scheduler in the longest period
   - SimpleTaskInstance etc have been almost entirely removed now, as we
     use the serialized versions
   
   ---
   **^ Add meaningful description above**
   
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/master/CONTRIBUTING.rst#pull-request-guidelines)** for more information.
   In case of fundamental code change, Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in [UPDATING.md](https://github.com/apache/airflow/blob/master/UPDATING.md).
   


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-700530503


   > I did indeed. For some reason (I thought sqlite was the default. I blame working late)
   
   It is the default, but breeze also persistently stores a few of the selections you've made last time (python version, database, dosckerhub user etc._ so that you do not have to add switches every time you run it. Simply running "breeze" will drop you to the environment you used last time.
   
   And it prints summary of those when you enter:
   
   ```
                                 Use CI image.
   
                                  Branch name:            master
                                  Docker image:           apache/airflow:master-python3.6-ci
                                  Airflow source version: 2.0.0.dev0
                                  Python version:         3.6
                                  DockerHub user:         apache
                                  DockerHub repo:         airflow
                                  Backend:                sqlite 
   
   Airflow core SQL connection: sqlite:////root/airflow/airflow.db
   ```
   
   Also what helps, you can run `breeze toggle-suppress-cheatsheet` and `breeze toggle-suppress-asciiart` to permanently disable both cheatsheet and the asciiart and then breeze will only show the "environment summary" when you enter  - this is easier to see it then.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489284780



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1707,53 +1343,119 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
-            try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
-        )
-        self._execute_task_instances(simple_dag_bag)
+    def _scheduler_loop_critical_section(self, dag_bag, session) -> Union[int, _NoLockObtained]:
+        """

Review comment:
       Yes -- I might also rename this method as a critical section has a meaning:
   
   > In concurrent programming, concurrent accesses to shared resources can lead to unexpected or erroneous behavior, so parts of the program where the shared resource is accessed need to be protected in ways that avoid the concurrent access. This protected section is the critical section or critical region
   
   But this entire function isn't critical any longer, just the execute part at the end.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703323056


   The CI and PROD Docker Images for the build are prepared in a separate "Build Image" workflow,
   that you will not see in the list of checks (you will see "Wait for images" jobs instead).
   
   You can checks the status of those images in [The workflow run](https://github.com/apache/airflow/actions/runs/288347334)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706265372


   Now there is only one more Grumpy Bot complaining: "Up-to-date Checker — PR is not up to date with master. Please rebase."
   
   


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-705009717


   > For me there are just two points left to be done in this or -> the bulk_sync_db and a question about task_instance [] left.
   
   Yup, on our list, will tackle shortly!


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-694946849


   Fantastic! I will have some time over the weekend to finally look through it myself :).


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-694169921


   One of the parts of this PR: it moves creating of DAG runs out of the dag file parser process, and in to the scheduler -- if you have a large number of dag files (1000, for instance), all with the same scheduler_interval, then the time to parse each one sequentially can introduce significant delay in creating the DAG runs after the period ticks over.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501249165



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       If we are using it only for tests (I suppose to set it to something other than -1) then wouldn't it be better to use something like `if unittest then...` as we already do in many places?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489366583



##########
File path: airflow/models/dag.py
##########
@@ -458,6 +458,99 @@ def previous_schedule(self, dttm):
         elif self.normalized_schedule_interval is not None:
             return timezone.convert_to_utc(dttm - self.normalized_schedule_interval)
 
+    def next_dagrun_info(self, date_last_automated_dagrun : Optional[pendulum.DateTime]):
+        """
+        Get information about the next DagRun of this dag after ``date_last_automated_dagrun`` -- the
+        execution date, and the earliest it could be scheduled
+
+        :param date_last_automated_dagrun: The max(execution_date) of existing
+            "automated" DagRuns for this dag (scheduled or backfill, but not
+            manual)
+        """
+        next_execution_date = self.next_dagrun_after_date(date_last_automated_dagrun)
+
+        if next_execution_date is None or self.schedule_interval in (None, '@once'):
+            return None
+
+        return {
+            'execution_date': next_execution_date,
+            'can_be_created_after': self.following_schedule(next_execution_date)
+        }
+
+    def next_dagrun_after_date(self, date_last_automated_dagrun: Optional[pendulum.DateTime]):
+        """
+        Get the next execution date after the given ``date_last_automated_dagrun``, acording to
+        schedule_interval, start_date, end_date etc.  This doesn't check max active run or any other
+        "concurrency" type limits, it only perofmrs calculations based on the varios date and interval fields
+        of this dag and it's tasks.
+
+        :param date_last_automated_dagrun: The execution_date of the last scheduler or
+            backfill triggered run for this dag
+        :type date_last_automated_dagrun: pendulum.Pendulum
+        """
+        if not self.schedule_interval:
+            return None
+
+        # don't schedule @once again
+        if self.schedule_interval == '@once' and date_last_automated_dagrun:
+            return None
+
+        # don't do scheduler catchup for dag's that don't have dag.catchup = True
+        if not (self.catchup or self.schedule_interval == '@once'):
+            # The logic is that we move start_date up until
+            # one period before, so that timezone.utcnow() is AFTER
+            # the period end, and the job can be created...
+            now = timezone.utcnow()
+            next_start = self.following_schedule(now)
+            last_start = self.previous_schedule(now)
+            if next_start <= now or isinstance(self.schedule_interval, timedelta):
+                new_start = last_start
+            else:
+                new_start = self.previous_schedule(last_start)
+
+            if self.start_date:
+                if new_start >= self.start_date:
+                    self.start_date = new_start
+            else:
+                self.start_date = new_start
+
+        next_run_date = None
+        if not date_last_automated_dagrun:
+            # First run
+            task_start_dates = [t.start_date for t in self.tasks]
+            if task_start_dates:
+                next_run_date = self.normalize_schedule(min(task_start_dates))
+                self.log.debug("Next run date based on tasks %s", next_run_date)
+        else:
+            next_run_date = self.following_schedule(date_last_automated_dagrun)
+
+        if date_last_automated_dagrun and next_run_date:
+            while next_run_date <= date_last_automated_dagrun:
+                next_run_date = self.following_schedule(next_run_date)
+
+        # don't ever schedule prior to the dag's start_date
+        if self.start_date:
+            next_run_date = self.start_date if not next_run_date else max(next_run_date, self.start_date)
+            if next_run_date == self.start_date:
+                next_run_date = self.normalize_schedule(self.start_date)
+
+            self.log.debug(
+                "Dag start date: %s. Next run date: %s",
+                self.start_date, next_run_date
+            )
+
+        # Don't schedule a dag beyond its end_date (as specified by the dag param)
+        if next_run_date and self.end_date and next_run_date > self.end_date:
+            return None
+
+        # Don't schedule a dag beyond its end_date (as specified by the task params)
+        # Get the min task end date, which may come from the dag.default_args
+        task_end_dates = [t.end_date for t in self.tasks if t.end_date]
+        if task_end_dates and next_run_date:
+            min_task_end_date = min(task_end_dates)
+            if next_run_date > min_task_end_date:
+                return None
+

Review comment:
       Err, yeah. This was a transcription error.
   
   ```suggestion
   
           return next_run_date
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499532238



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -867,122 +631,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
-            self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
+            self.execute_callbacks(dagbag, callback_requests)

Review comment:
       The `except Exception` here should moved to inside of the execute_callbacks, so that failure in one callback will not drop all other callbacks.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -867,122 +631,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
-            self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
+            self.execute_callbacks(dagbag, callback_requests)

Review comment:
       The `except Exception` here should be moved to inside of the execute_callbacks, so that failure in one callback will not drop all other callbacks.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501914789



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -567,302 +567,71 @@ def update_import_errors(session: Session, dagbag: DagBag) -> None:
                 stacktrace=stacktrace))
         session.commit()
 
-    # pylint: disable=too-many-return-statements,too-many-branches
     @provide_session
-    def create_dag_run(
-        self,
-        dag: DAG,
-        dag_runs: Optional[List[DagRun]] = None,
-        session: Session = None,
-    ) -> Optional[DagRun]:
-        """
-        This method checks whether a new DagRun needs to be created
-        for a DAG based on scheduling interval.
-        Returns DagRun if one is scheduled. Otherwise returns None.
-        """
-        # pylint: disable=too-many-nested-blocks
-        if not dag.schedule_interval:
-            return None
-
-        active_runs: List[DagRun]
-        if dag_runs is None:
-            active_runs = DagRun.find(
-                dag_id=dag.dag_id,
-                state=State.RUNNING,
-                external_trigger=False,
-                session=session
-            )
-        else:
-            active_runs = [
-                dag_run
-                for dag_run in dag_runs
-                if not dag_run.external_trigger
-            ]
-        # return if already reached maximum active runs and no timeout setting
-        if len(active_runs) >= dag.max_active_runs and not dag.dagrun_timeout:
-            return None
-        timed_out_runs = 0
-        for dr in active_runs:
-            if (
-                dr.start_date and dag.dagrun_timeout and
-                dr.start_date < timezone.utcnow() - dag.dagrun_timeout
-            ):
-                dr.state = State.FAILED
-                dr.end_date = timezone.utcnow()
-                dag.handle_callback(dr, success=False, reason='dagrun_timeout',
-                                    session=session)
-                timed_out_runs += 1
-        session.commit()
-        if len(active_runs) - timed_out_runs >= dag.max_active_runs:
-            return None
-
-        # this query should be replaced by find dagrun
-        last_scheduled_run: Optional[datetime.datetime] = (
-            session.query(func.max(DagRun.execution_date))
-            .filter_by(dag_id=dag.dag_id)
-            .filter(or_(
-                DagRun.external_trigger == False,  # noqa: E712 pylint: disable=singleton-comparison
-                DagRun.run_type == DagRunType.SCHEDULED.value
-            )).scalar()
-        )
-
-        # don't schedule @once again
-        if dag.schedule_interval == '@once' and last_scheduled_run:
-            return None
-
-        # don't do scheduler catchup for dag's that don't have dag.catchup = True
-        if not (dag.catchup or dag.schedule_interval == '@once'):
-            # The logic is that we move start_date up until
-            # one period before, so that timezone.utcnow() is AFTER
-            # the period end, and the job can be created...
-            now = timezone.utcnow()
-            next_start = dag.following_schedule(now)
-            last_start = dag.previous_schedule(now)
-            if next_start <= now or isinstance(dag.schedule_interval, timedelta):
-                new_start = last_start
-            else:
-                new_start = dag.previous_schedule(last_start)
-
-            if dag.start_date:
-                if new_start >= dag.start_date:
-                    dag.start_date = new_start
-            else:
-                dag.start_date = new_start
-
-        next_run_date = None
-        if not last_scheduled_run:
-            # First run
-            task_start_dates = [t.start_date for t in dag.tasks]
-            if task_start_dates:
-                next_run_date = dag.normalize_schedule(min(task_start_dates))
-                self.log.debug(
-                    "Next run date based on tasks %s",
-                    next_run_date
-                )
-        else:
-            next_run_date = dag.following_schedule(last_scheduled_run)
-
-        # make sure backfills are also considered
-        last_run = dag.get_last_dagrun(session=session)
-        if last_run and next_run_date:
-            while next_run_date <= last_run.execution_date:
-                next_run_date = dag.following_schedule(next_run_date)
-
-        # don't ever schedule prior to the dag's start_date
-        if dag.start_date:
-            next_run_date = (dag.start_date if not next_run_date
-                             else max(next_run_date, dag.start_date))
-            if next_run_date == dag.start_date:
-                next_run_date = dag.normalize_schedule(dag.start_date)
-
-            self.log.debug(
-                "Dag start date: %s. Next run date: %s",
-                dag.start_date, next_run_date
-            )
-
-        # don't ever schedule in the future or if next_run_date is None
-        if not next_run_date or next_run_date > timezone.utcnow():
-            return None
-
-        # this structure is necessary to avoid a TypeError from concatenating
-        # NoneType
-        period_end = None
-        if dag.schedule_interval == '@once':
-            period_end = next_run_date
-        elif next_run_date:
-            period_end = dag.following_schedule(next_run_date)
-
-        # Don't schedule a dag beyond its end_date (as specified by the dag param)
-        if next_run_date and dag.end_date and next_run_date > dag.end_date:
-            return None
-
-        # Don't schedule a dag beyond its end_date (as specified by the task params)
-        # Get the min task end date, which may come from the dag.default_args
-        min_task_end_date = min([t.end_date for t in dag.tasks if t.end_date], default=None)
-        if next_run_date and min_task_end_date and next_run_date > min_task_end_date:
-            return None
-
-        if next_run_date and period_end and period_end <= timezone.utcnow():
-            next_run = dag.create_dagrun(
-                run_type=DagRunType.SCHEDULED,
-                execution_date=next_run_date,
-                start_date=timezone.utcnow(),
-                state=State.RUNNING,
-                external_trigger=False
-            )
-            return next_run
-
-        return None
-
-    @provide_session
-    def _process_task_instances(
-        self, dag: DAG, dag_runs: List[DagRun], session: Session = None
-    ) -> List[TaskInstanceKey]:
-        """
-        This method schedules the tasks for a single DAG by looking at the
-        active DAG runs and adding task instances that should run to the
-        queue.
-        """
-        # update the state of the previously active dag runs
-        active_dag_runs = 0
-        task_instances_list = []
-        for run in dag_runs:
-            self.log.info("Examining DAG run %s", run)
-            # don't consider runs that are executed in the future unless
-            # specified by config and schedule_interval is None
-            if run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
-                self.log.error(
-                    "Execution date is in future: %s",
-                    run.execution_date
-                )
-                continue
-
-            if active_dag_runs >= dag.max_active_runs:
-                self.log.info("Number of active dag runs reached max_active_run.")
-                break
-
-            # skip backfill dagruns for now as long as they are not really scheduled
-            if run.is_backfill:
-                continue
-
-            # todo: run.dag is transient but needs to be set
-            run.dag = dag  # type: ignore
-            # todo: preferably the integrity check happens at dag collection time
-            run.verify_integrity(session=session)
-            ready_tis = run.update_state(session=session)
-            if run.state == State.RUNNING:
-                active_dag_runs += 1
-                self.log.debug("Examining active DAG run: %s", run)
-                for ti in ready_tis:
-                    self.log.debug('Queuing task: %s', ti)
-                    task_instances_list.append(ti.key)
-        return task_instances_list
-
-    @provide_session
-    def _process_dags(self, dags: List[DAG], session: Session = None) -> List[TaskInstanceKey]:
-        """
-        Iterates over the dags and processes them. Processing includes:
-
-        1. Create appropriate DagRun(s) in the DB.
-        2. Create appropriate TaskInstance(s) in the DB.
-        3. Send emails for tasks that have missed SLAs (if CHECK_SLAS config enabled).
-
-        :param dags: the DAGs from the DagBag to process
-        :type dags: List[airflow.models.DAG]
-        :rtype: list[TaskInstance]
-        :return: A list of generated TaskInstance objects
-        """
-        check_slas: bool = conf.getboolean('core', 'CHECK_SLAS', fallback=True)
-        use_job_schedule: bool = conf.getboolean('scheduler', 'USE_JOB_SCHEDULE')
-
-        # pylint: disable=too-many-nested-blocks
-        tis_out: List[TaskInstanceKey] = []
-        dag_ids: List[str] = [dag.dag_id for dag in dags]
-        dag_runs = DagRun.find(dag_id=dag_ids, state=State.RUNNING, session=session)
-        # As per the docs of groupby (https://docs.python.org/3/library/itertools.html#itertools.groupby)
-        # we need to use `list()` otherwise the result will be wrong/incomplete
-        dag_runs_by_dag_id: Dict[str, List[DagRun]] = {
-            k: list(v) for k, v in groupby(dag_runs, lambda d: d.dag_id)
-        }
-
-        for dag in dags:
-            dag_id: str = dag.dag_id
-            self.log.info("Processing %s", dag_id)
-            dag_runs_for_dag = dag_runs_by_dag_id.get(dag_id) or []
-
-            # Only creates DagRun for DAGs that are not subdag since
-            # DagRun of subdags are created when SubDagOperator executes.
-            if not dag.is_subdag and use_job_schedule:
-                dag_run = self.create_dag_run(dag, dag_runs=dag_runs_for_dag)
-                if dag_run:
-                    dag_runs_for_dag.append(dag_run)
-                    expected_start_date = dag.following_schedule(dag_run.execution_date)
-                    if expected_start_date:
-                        schedule_delay = dag_run.start_date - expected_start_date
-                        Stats.timing(
-                            'dagrun.schedule_delay.{dag_id}'.format(dag_id=dag.dag_id),
-                            schedule_delay)
-                    self.log.info("Created %s", dag_run)
-
-            if dag_runs_for_dag:
-                tis_out.extend(self._process_task_instances(dag, dag_runs_for_dag))
-                if check_slas:
-                    self.manage_slas(dag)
-
-        return tis_out
-
-    def _find_dags_to_process(self, dags: List[DAG]) -> List[DAG]:
-        """
-        Find the DAGs that are not paused to process.
-
-        :param dags: specified DAGs
-        :return: DAGs to process
-        """
-        if self.dag_ids:
-            dags = [dag for dag in dags
-                    if dag.dag_id in self.dag_ids]
-        return dags
-
-    @provide_session
-    def execute_on_failure_callbacks(
+    def execute_callbacks(
         self,
         dagbag: DagBag,
-        failure_callback_requests: List[FailureCallbackRequest],
+        callback_requests: List[CallbackRequest],
         session: Session = None
     ) -> None:
         """
         Execute on failure callbacks. These objects can come from SchedulerJob or from
         DagFileProcessorManager.
 
-        :param failure_callback_requests: failure callbacks to execute
-        :type failure_callback_requests: List[airflow.utils.dag_processing.FailureCallbackRequest]
+        :param dagbag: Dag Bag of dags
+        :param callback_requests: failure callbacks to execute
+        :type callback_requests: List[airflow.utils.callback_requests.CallbackRequest]
         :param session: DB session.
         """
-        for request in failure_callback_requests:
-            simple_ti = request.simple_task_instance
-            if simple_ti.dag_id in dagbag.dags:
-                dag = dagbag.dags[simple_ti.dag_id]
-                if simple_ti.task_id in dag.task_ids:
-                    task = dag.get_task(simple_ti.task_id)
-                    ti = TI(task, simple_ti.execution_date)
-                    # Get properties needed for failure handling from SimpleTaskInstance.
-                    ti.start_date = simple_ti.start_date
-                    ti.end_date = simple_ti.end_date
-                    ti.try_number = simple_ti.try_number
-                    ti.state = simple_ti.state
-                    ti.test_mode = self.UNIT_TEST_MODE
+        for request in callback_requests:
+            try:
+                if isinstance(request, TaskCallbackRequest):
+                    self._execute_task_callbacks(dagbag, request)
+                elif isinstance(request, SlaCallbackRequest):
+                    self.manage_slas(dagbag.dags.get(request.dag_id))
+                elif isinstance(request, DagCallbackRequest):
+                    self._execute_dag_callbacks(dagbag, request, session)
+            except Exception:  # pylint: disable=broad-except
+                self.log.exception("Error executing callback for File: %s", request.full_filepath)

Review comment:
       Will do




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r493515364



##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()
         except IntegrityError as err:
             self.log.info(str(err))
             self.log.info('Hit IntegrityError while creating the TIs for '
                           f'{dag.dag_id} - {self.execution_date}.')
             self.log.info('Doing session rollback.')
+            # TODO[HA]: We probaly need to savepoint this so we can keep the transaction alive.

Review comment:
       One side note. Should we rename verify_integrity to some different name ? Seems that this method not only verify the integrity of the dagrun and connected task instances but it also creates task instances were they are missing. Maybe "synchronize_task_instances" or something like that.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499494587



##########
File path: airflow/models/dag.py
##########
@@ -1572,6 +1661,21 @@ def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
             session.add(orm_dag)
             orm_dags.append(orm_dag)
 
+        # Get the latest dag run for each existing dag as a single query (avoid n+1 query)
+        most_recent_dag_runs = dict(session.query(DagRun.dag_id, func.max_(DagRun.execution_date)).filter(
+            DagRun.dag_id.in_(existing_dag_ids),
+            or_(
+                DagRun.run_type == DagRunType.BACKFILL_JOB.value,
+                DagRun.run_type == DagRunType.SCHEDULED.value,
+            ),
+        ).group_by(DagRun.dag_id).all())
+
+        num_active_runs = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_(existing_dag_ids),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False)
+        ).group_by(DagRun.dag_id).all())

Review comment:
       I wonder if it should be done in this method.  This method only talks about data synchronization, not updating other fields. See: https://github.com/apache/airflow/pull/10956#discussion_r489347417




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502470029



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -899,122 +667,54 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
-
-        try:
-            self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
-        except Exception:  # pylint: disable=broad-except
-            self.log.exception("Error executing failure callback!")
-
-        # Save individual DAGs in the ORM and update DagModel.last_scheduled_time
-        dagbag.sync_to_db()
-
-        paused_dag_ids = DagModel.get_paused_dag_ids(dag_ids=dagbag.dag_ids)
-
-        unpaused_dags: List[DAG] = [
-            dag for dag_id, dag in dagbag.dags.items() if dag_id not in paused_dag_ids
-        ]
-
-        serialized_dags = self._prepare_serialized_dags(unpaused_dags, pickle_dags, session)
+            return 0, len(dagbag.import_errors)
+
+        self.execute_callbacks(dagbag, callback_requests)
+
+        # Save individual DAGs in the ORM
+        dagbag.read_dags_from_db = True
+
+        # Retry 'dagbag.sync_to_db()' in case of any Operational Errors
+        # In case of failures, provide_session handles rollback
+        for attempt in tenacity.Retrying(
+            retry=tenacity.retry_if_exception_type(exception_types=OperationalError),
+            wait=tenacity.wait_random_exponential(multiplier=0.5, max=5),
+            stop=tenacity.stop_after_attempt(settings.MAX_DB_RETRIES),
+            before_sleep=tenacity.before_sleep_log(self.log, logging.DEBUG),
+            reraise=True
+        ):
+            with attempt:
+                self.log.debug(
+                    "Running dagbag.sync_to_db with retries. Try %d of %d",
+                    attempt.retry_state.attempt_number,
+                    settings.MAX_DB_RETRIES
+                )
+                dagbag.sync_to_db()
 
-        dags = self._find_dags_to_process(unpaused_dags)
+        if pickle_dags:
+            paused_dag_ids = DagModel.get_paused_dag_ids(dag_ids=dagbag.dag_ids)
 
-        ti_keys_to_schedule = self._process_dags(dags, session)
+            unpaused_dags: List[DAG] = [
+                dag for dag_id, dag in dagbag.dags.items() if dag_id not in paused_dag_ids
+            ]
 
-        self._schedule_task_instances(dagbag, ti_keys_to_schedule, session)
+            for dag in unpaused_dags:
+                dag.pickle(session)

Review comment:
       Nice. Changed in 36e23f613




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500618913



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       Yea that works but would be still good to separate the setting of `next_dagrun` to an internal method too and updating the docstrings to reflect that it sets next dagruns too




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502479216



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -868,122 +608,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
             self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Error executing failure callback!")
 
-        # Save individual DAGs in the ORM and update DagModel.last_scheduled_time
+        # Save individual DAGs in the ORM
+        dagbag.read_dags_from_db = True

Review comment:
       @turbaszek can you say something more? I see you closed this conversation. 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499498673



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1714,53 +1321,158 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to

Review comment:
       Agree. It would be great to refer to the config value (which is already there and have useful comment about why you want to modify this value).




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r493478012



##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(10).with_for_update(of=cls, **skip_locked(session=session))

Review comment:
       This limit is a bit out of a blue and I think it's not good that we have it hard-coded here. While I understand why we want to have it (we want to repeat scheduler loops more frequently and only process them in "batches" - It would be great to dwo two things:
   
   1) to extract it as a meaningful constant with an explanation why 10 is a good value
   2) or - better - to calculate it based on some criteria if this value should depend on something
   
   Also we need to check (and understand) what happens if we are increasing this value. Do we risk higher memory consumptions? Or deadlocks ? or any other risks? What are we trying to prevent here?  
   
   I understand this is an empirical value, but I think we should justify this value.

##########
File path: airflow/models/dagrun.py
##########
@@ -75,6 +80,8 @@ class DagRun(Base, LoggingMixin):
         backref=backref('dag_run', uselist=False),
     )
 
+    DEFAULT_DAGRUNS_TO_EXAMINE = airflow_conf.getint('scheduler', 'max_dagruns_per_query', fallback=20)

Review comment:
       Same here. The 20 value is a bit magical and we need to know where it comes from and what are the consequences of changing the values. Ideally some test results would be great to show what can happen if we decrease it. It is also a bit strange that his 20 here is not hard-coded, where the 10 in the "next_dagrun" is. What's the reasoning behind one being hard-coded and the other being configurable. 

##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()
         except IntegrityError as err:
             self.log.info(str(err))
             self.log.info('Hit IntegrityError while creating the TIs for '
                           f'{dag.dag_id} - {self.execution_date}.')
             self.log.info('Doing session rollback.')
+            # TODO[HA]: We probaly need to savepoint this so we can keep the transaction alive.

Review comment:
       On a side not. Should we rename verify_integrity to some different name ? Seems that this method not only verify the integrity of the dagrun and connected task instances but it also creates task instances were they are missing. Maybe "synchronize_task_instances" or something like that.

##########
File path: airflow/models/dagrun.py
##########
@@ -344,6 +393,9 @@ def update_state(self, session: Session = None) -> List[TI]:
         leaf_task_ids = {t.task_id for t in dag.leaves}
         leaf_tis = [ti for ti in tis if ti.task_id in leaf_task_ids]
 
+        # TODO[ha]: These callbacks shouldn't run in the scheduler loop - check if Kamil changed this to run

Review comment:
       We should indeed move it outside of the scheduler loop to a DAG processor. And possibly  send it to DagFileProcessor like Kamil did. 
   
   This shoud actually help a lot if this is all within the uncommitted transaction. Those callbacks are potentialy problematic

##########
File path: airflow/models/dagrun.py
##########
@@ -313,14 +360,16 @@ def update_state(self, session: Session = None) -> List[TI]:
         :rtype ready_tis: list[airflow.models.TaskInstance]
         """
 
+        start_dttm = timezone.utcnow()

Review comment:
       Should we change this method to also update state of the tasks? I think it is only used in two places (schedule_job and backfill_job) and the "update_state" method returning tasks sounds a bit weird. I'd rather think about update the task instances as well when update_state is run so that it is all encapsulated within one "update_state" method.

##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),

Review comment:
       What happens if next _dagrun_create_after is None (because it is set to None in update_dag_next_dagrun(). Will they be skipped? Is there any other place where those are selected ?

##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()

Review comment:
       What's the reason for the integration error here? Is the Integrity error here still valid if we do not commit to the database? I think flush is not likely to generate Integrity Error at all.
   
   Shoudl we start caring about isolation level of the transactions we have ? Will it work when we have different isolation levels set ?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492161940



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       nit: we can create a context manager that will make sure that the transaction is not committed in the code block.
   ```python
   with keep_traansaction():
        ....
   ```
   ```python
   with prohibit_commit():
        ....
   ```
   The effect will be the same, but the intention will be easier to understand.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] raphaelauv commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
raphaelauv commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-736528282


   @ashb One more question , how do we custom the number of threads ( that are in practice processes because of the GIL )  of the scheduler  ?
   
   there is no more max_threads in http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/latest/configurations-ref.html#scheduler
   
   Thank you


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492341310



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       I don't think this is (easily) detectable with static checks -- for instance if you call a method with the `@provide_session` decorator and forget to pass it a `session=session` param, then you will end up committing by mistake.
   
   (I was a little bit surprised by this, as I thought it should be a new or perhaps it's using a different DB connection but the events are bound to all sessions, not just one instance)
   
   It feels like a lot of work, and not 100% reliable, to write a custom pylint check when an `if not self.unit_test_mode` would have the same effect.
   

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Thinking more about it, a simpler rule would be easier:
   
   If a function has `@provide_session`, it must not do `session.commit()` -- only `session.flush()` is allowed.
   
   My thinking here is:
   
   - If passed an existing session, the caller is responsible for committing when they choose
   - If not passed a session, then `@provide_session` will commit for us anyway.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499557790



##########
File path: tests/www/test_views.py
##########
@@ -639,10 +638,10 @@ def test_view_uses_existing_dagbag(self, endpoint):
         self.check_content_in_response('example_bash_operator', resp)
 
     @parameterized.expand([
-        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}}'),
-        ("hello'world", r'\"conf\":{\"abc\":\"hello\\u0027world\"}}'),
-        ("<script>", r'\"conf\":{\"abc\":\"\\u003cscript\\u003e\"}}'),
-        ("\"", r'\"conf\":{\"abc\":\"\\\"\"}}'),
+        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}'),

Review comment:
       Nit: Is it related? It made me think because there was a change in the airflow.www package and I did not expect it.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499826337



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1714,53 +1321,158 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to

Review comment:
       Do you think this would be the best place to document it, or in the "DagRun.next_dagruns_to_examine" method?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499574583



##########
File path: tests/www/test_views.py
##########
@@ -639,10 +638,10 @@ def test_view_uses_existing_dagbag(self, endpoint):
         self.check_content_in_response('example_bash_operator', resp)
 
     @parameterized.expand([
-        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}}'),
-        ("hello'world", r'\"conf\":{\"abc\":\"hello\\u0027world\"}}'),
-        ("<script>", r'\"conf\":{\"abc\":\"\\u003cscript\\u003e\"}}'),
-        ("\"", r'\"conf\":{\"abc\":\"\\\"\"}}'),
+        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}'),

Review comment:
       Yes, see https://github.com/apache/airflow/pull/10956#discussion_r499574149




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501095203



##########
File path: tests/jobs/test_backfill_job.py
##########
@@ -160,10 +160,11 @@ def test_trigger_controller_dag(self):
         )
         job.run()
 
-        task_instances_list = dag_file_processor._process_task_instances(
-            target_dag,
-            dag_runs=DagRun.find(dag_id='example_trigger_target_dag')
-        )
+        task_instances_list = []

Review comment:
       This one is left I think @ashb?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-700525412


   > You probably forgot to change backend to sqlite when you run breeze.
   
   I did indeed. For some reason (I thought sqlite was the default. I blame working late)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499518288



##########
File path: airflow/models/dagrun.py
##########
@@ -313,14 +360,16 @@ def update_state(self, session: Session = None) -> List[TI]:
         :rtype ready_tis: list[airflow.models.TaskInstance]
         """
 
+        start_dttm = timezone.utcnow()

Review comment:
       Any further thoughts ?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500609191



##########
File path: airflow/config_templates/config.yml
##########
@@ -1562,6 +1562,41 @@
       type: string
       example: ~
       default: "512"
+    - name: use_row_level_locking
+      description: |
+        Should the scheduler issue `SELECT ... FOR UPDATE` in relevant queries.
+        If this is set to False then you should not run more than a single
+        scheduler at once
+      version_added: 2.0.0
+      type: boolean
+      example: ~
+      default: "True"
+    - name: max_dagruns_to_create_per_loop
+      description: |
+        This changes the number of dags that are locked by each scheduler when
+        creating dag runs. One possible reason for setting this lower is if you
+        have huge dags and are running multiple schedules, you won't want one
+        scheduler to do all the work.
+
+        Default: 10
+      example: ~
+      version_added: 2.0.0
+      type: string
+      default: ~
+    - name: max_dagruns_per_loop_to_schedule
+      description: |
+        How many DagRuns should a scheduler exaimne (and lock) when scheduling
+        and queuing tasks. Increasing this limit will allow more throughput for
+        smaller DAGs but will likely slow down throughput for larger (>500
+        tasks for example.) DAGs. Setting this to high when using multiple

Review comment:
       :face_with_head_bandage: Working late never pays off. I'll fix this in the morning :laughing: 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706261725


   
   > > Still fewer comments than #4938
   > 
   > I am afraid @mik-laj beat me already with #8721, so you are not even close to the podium @ashb
   
   Oh man, Github does a bad job of ordering by number of comments!


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-701053868


   Ran some benchmarks against different versions (more comprehensive benchmarks will be provided -- consider this too as **_preliminary_**):
   
   **Scenario**: 10 Dag File | 1 Dag Per File | 10 Tasks per DAG
   **Configs**:
   - Executor: CeleryExecutor
   - Parallelism: 128
   - Workers: 4 (1 CPU - 3.75 GB memory)
   - Each Scheduler (1 CPU - 3.75 GB memory)
   
   **Airflow 1.10.10**
   TI Lag Avg: 64.845s  (± 7.995) 
   Time in Queued State: 57.6485s (± 7.395)
   
   **Airflow Master**
   TI Lag Avg: 48.5754s (± 62.991) 
   Time in Queued State: 11.909s (± 8.252)
   
   **This PR** (Single Scheduler)
   TI Lag Avg: 10.262s (± 5.299) 
   Time in Queued State: 9.3494s (± 5.355)
   
   ------
   
   **Scenario**: 100 Dag Files | 1 Dag Per File | 10 Tasks per DAG
   **Configs**:
   - Executor: CeleryExecutor
   - Parallelism: 128
   - Workers: 4 (1 CPU - 3.75 GB memory)
   - Each Scheduler (1 CPU - 3.75 GB memory)
   
   
   **Airflow 1.10.10**
   TI Lag Avg: 809.537s (± 29.6730) 
   Time in Queued State: 68.708s (± 15.5567)
   
   **Airflow Master**
   TI Lag Avg: 392.806s (± 318.620) 
   Time in Queued State: 10.694s (± 9.930)
   
   **This PR (with 2 Schedulers)**
   TI Lag Avg: 74.028s (± 17.215) 
   Time in Queued State: 68.708s (± 15.556)
   
   
   


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] XD-DENG commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
XD-DENG commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r490526192



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1714,53 +1321,158 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to

Review comment:
       Minor: May be worth mentioning this default value "20" can be adjusted via configuration item `scheduler.max_dagruns_per_query`. Not for _users_, but for _developers_ reading this part later.

##########
File path: airflow/models/dag.py
##########
@@ -458,6 +458,101 @@ def previous_schedule(self, dttm):
         elif self.normalized_schedule_interval is not None:
             return timezone.convert_to_utc(dttm - self.normalized_schedule_interval)
 
+    def next_dagrun_info(self, date_last_automated_dagrun : Optional[pendulum.DateTime]):
+        """
+        Get information about the next DagRun of this dag after ``date_last_automated_dagrun`` -- the
+        execution date, and the earliest it could be scheduled
+
+        :param date_last_automated_dagrun: The max(execution_date) of existing
+            "automated" DagRuns for this dag (scheduled or backfill, but not
+            manual)
+        """
+        next_execution_date = self.next_dagrun_after_date(date_last_automated_dagrun)
+
+        if next_execution_date is None or self.schedule_interval in (None, '@once'):
+            return None
+
+        return {
+            'execution_date': next_execution_date,
+            'can_be_created_after': self.following_schedule(next_execution_date)
+        }

Review comment:
       Not sure, but may be cleaner to return a tuple instead. Say line 473 will be `return None, None`, and line 475 becomes `return next_execution_date, self.following_schedule(next_execution_date)`
   
   In such a way, calling also becomes simpler
   
   ```python
   orm_dag.next_dagrun, orm_dag.next_dagrun_create_after = dag.next_dagrun_info(xxx)
   ```
   
   Of course quite subjective opinion, so feel free to ignore

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1464,23 +1070,21 @@ def _execute_task_instances(
         2. Change the state for the TIs above atomically.
         3. Enqueue the TIs in the executor.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        HA note: This function is a "critical section" meaning that only a single executor process can execute
+        this function at the same time. This is achived by doing ``SELECT ... from pool FOR UPDATE``. For DBs

Review comment:
       typo "achived" -> "achieved"




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492170144



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Sure, will create a txn manager.
   
   I think keeping it for unit/integration tests is the right thing to do, I'm open to discussion if we should remove it for "runtime".




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb edited a comment on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706266033


   Man I was _just_ about to merge it too :)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499575925



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -867,122 +631,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
-            self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
+            self.execute_callbacks(dagbag, callback_requests)

Review comment:
       Good call, will do




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501529477



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       It's not used in every test is the issue, so we don't want to always set it when unittest is enabled.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499574149



##########
File path: tests/www/test_views.py
##########
@@ -639,10 +638,10 @@ def test_view_uses_existing_dagbag(self, endpoint):
         self.check_content_in_response('example_bash_operator', resp)
 
     @parameterized.expand([
-        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}}'),
-        ("hello'world", r'\"conf\":{\"abc\":\"hello\\u0027world\"}}'),
-        ("<script>", r'\"conf\":{\"abc\":\"\\u003cscript\\u003e\"}}'),
-        ("\"", r'\"conf\":{\"abc\":\"\\\"\"}}'),
+        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}'),

Review comment:
       Extra params now appear in the output, so the closing `}` is now a `,`.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-701053868


   Ran some benchmarks against different versions (more comprehensive benchmarks will be provided -- consider this too as **_preliminary_**):
   
   **Scenario**: 10 Dag File | 1 Dag Per File | 10 Tasks per DAG
   **Configs**:
   - Executor: CeleryExecutor
   - Parallelism: 128
   - Workers: 4 (1 CPU - 3.75 GB memory)
   - Each Scheduler (1 CPU - 3.75 GB memory)
   
   **Airflow 1.10.10**
   TI Lag Avg: 64.845s  (± 7.995) 
   Time in Queued State: 57.6485s (± 7.395)
   
   **Airflow Master**
   TI Lag Avg: 48.5754s (± 62.991) 
   Time in Queued State: 11.909s (± 8.252)
   
   **This PR** (Single Scheduler)
   TI Lag Avg: 10.262s (± 5.299) 
   Time in Queued State: 9.3494s (± 5.355)
   
   ------
   
   **Scenario**: 100 Dag Files | 1 Dag Per File | 10 Tasks per DAG
   **Configs**:
   - Executor: CeleryExecutor
   - Parallelism: 128
   - Workers: 4 (1 CPU - 3.75 GB memory)
   - Each Scheduler (1 CPU - 3.75 GB memory)
   
   
   **Airflow 1.10.10**
   TI Lag Avg: 809.537s (± 29.6730) 
   Time in Queued State: 751.241s (± 35.5153)
   
   **Airflow Master**
   TI Lag Avg: 392.806s (± 318.620) 
   Time in Queued State: 10.694s (± 9.930)
   
   **This PR (with 2 Schedulers)**
   TI Lag Avg: 74.028s (± 17.215) 
   Time in Queued State: 68.708s (± 15.556)
   
   
   


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492171471



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),

Review comment:
       Exceeding unlikely (Maybe if you deleted the dag_run via the Browse -> DagRuns, I think that used to be possible but isn't anymore), but the existing code allowed it, and we have unit tests that check for it, so to keep this change smaller I didn't remove it.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] KevinYang21 commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
KevinYang21 commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491672443



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control

Review comment:
       Got it. I guess then we need some more checks in the caller--currently I haven't noticed other checks except checking the existence of `next_dagrun_create_after` value before we come here create the DAG run. The test `test_runs_respected_after_clear` I think covers part of it, it checks the scheduling part but even if it passed (which I don't think it will given that[ it returns directly when active run > max run](https://github.com/apache/airflow/pull/10956/files/f3c6cf1dc10e509da1b3b1db2a595a58abfab847#diff-c35269bcfbbe386e269ffa7487e86192R1492-R1498) rather than before[ active run += 1 after the run is processed](https://github.com/apache/airflow/pull/10956/files/f3c6cf1dc10e509da1b3b1db2a595a58abfab847#diff-c35269bcfbbe386e269ffa7487e86192L723)), we can still create an extra DAG run here.
   

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       Thank you Ash for the pointer, I think the trigger rule deps check query optimization is very nice and should help a lot. Though I'd still be skeptical about it would reduce the lag to a neglegible degree. I can have that commit cherry-picked soon and share some stats soon.
   
   But I totally understand that if we can bring all the scheduling logic to the master loop and make it fast then it would be a game changer for scheduling delay--it wasn't too big of an issue for us as our customers are okish to have their DAG file parsed every 2 mins :D (there can be a couple more similar optimization on dep checks that we can try to get a reasonable performance)
   
   We have definitely ran into the timeout issue, for that particular DAG file we set the timeout to be like 20 mins and had an alert set up to catch similar cases.
   
   For the UI part, the DAG wasn't being able to load but the customers got used to it--it has been in this state for >3 years :) I think going beyond a couple k tasks, the DAG starts to be a pain to look at in the UI and people use quick links to go to subdags or root at a sub tree.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)

Review comment:
       Cool. Faster in the sense that this scheduling loop should run faster/more frequently than the DAG processor loop, which DAG runs were created before?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489378591



##########
File path: airflow/executors/base_executor.py
##########
@@ -69,16 +70,16 @@ def start(self):  # pragma: no cover
         """
 
     def queue_command(self,
-                      simple_task_instance: SimpleTaskInstance,

Review comment:
       Yes, and we're almost there with this PR, but not quite -- it's still used for sending messages/failure callback requests _down_ to the Parsing process.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499832547



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       I still have some more testing to do here, but between https://github.com/apache/airflow/pull/4751 and https://github.com/apache/airflow/pull/11147 this part of the code is a lot quicker than early 1.10.x that Kevin is based off.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494942465



##########
File path: airflow/models/dagrun.py
##########
@@ -313,14 +360,16 @@ def update_state(self, session: Session = None) -> List[TI]:
         :rtype ready_tis: list[airflow.models.TaskInstance]
         """
 
+        start_dttm = timezone.utcnow()

Review comment:
       Already had that thought :) 
   https://github.com/apache/airflow/blob/b28d67332bb052441bc2ffd00030d620aac381c8/airflow/jobs/scheduler_job.py#L1565-L1567




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502468772



##########
File path: tests/jobs/test_backfill_job.py
##########
@@ -160,10 +160,11 @@ def test_trigger_controller_dag(self):
         )
         job.run()
 
-        task_instances_list = dag_file_processor._process_task_instances(
-            target_dag,
-            dag_runs=DagRun.find(dag_id='example_trigger_target_dag')
-        )
+        task_instances_list = []

Review comment:
       Fixed in ce51c264f




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706258940


   > Still fewer comments than #4938
   
   I am afraid @mik-laj beat me already with #8721, so you are not even close the podium @ashb 


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r498462189



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/ef9101ff910eba85a2782f894f0e9dfbafc04689




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-700530503


   > I did indeed. For some reason (I thought sqlite was the default. I blame working late)
   
   It is the default, but breeze also persistently stores a few of the selections you've made last time (python version, database, dosckerhub user etc._ so that you do not have to add switches every time you run it. Simply running "breeze" will drop you to the environment you used last time.
   
   And it prints summary of those when you enter:
   
   ```
                                 Use CI image.
   
                                  Branch name:            master
                                  Docker image:           apache/airflow:master-python3.6-ci
                                  Airflow source version: 2.0.0.dev0
                                  Python version:         3.6
                                  DockerHub user:         apache
                                  DockerHub repo:         airflow
                                  Backend:                sqlite 
   
   Airflow core SQL connection: sqlite:////root/airflow/airflow.db
   ```
   
   Also what helps, you can run `breeze toggle-suppress-cheatsheet` and `breeze toggle-suppress-asciiart` to permanently disable both cheatsheet and the asciiart and they it will only show the "environment summary" when you enter  - this is easier to see it then.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502507259



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1749,62 +1403,353 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if loop_count >= self.num_runs > 0:
+                self.log.info(
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
+                )
+                break
             if self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested DAG parse count (%d) has been reached after %d "
+                    " scheduler loops",
+                    self.num_times_parse_dags, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+          Since creating Dag Runs is a relatively time consuming process, we select only 10 dags by default
+          (configurable via ``scheduler.max_dagruns_to_create_per_loop`` setting) - putting this higher will
+          mean one scheduler could spend a chunk of time creating dag runs, and not ever get around to
+          scheduling tasks.
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default, configurable
+          via ``scheduler.max_dagruns_per_loop_to_schedule`` config setting) and tries to progress state (TIs
+          to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+          The reason we don't select all dagruns at once because the rows are selected with row locks, meaning
+          that only one scheduler can "process them", even it it is waiting behind other dags. Increasing this
+          limit will allow more throughput for smaller DAGs but will likely slow down throughput for larger
+          (>500 tasks.) DAGs
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        # Put a check in place to make sure we don't commit unexpectedly
+        with prohibit_commit(session) as guard:
+
+            if settings.USE_JOB_SCHEDULE:
+                query = DagModel.dags_needing_dagruns(session)
+                self._create_dag_runs(query.all(), session)
+
+                # commit the session - Release the write lock on DagModel table.
+                guard.commit()
+                # END: create dagruns
+
+            dag_runs = DagRun.next_dagruns_to_examine(session)
+
+            # Bulk fetch the currently active dag runs for the dags we are
+            # examining, rather than making one query per DagRun
+
+            # TODO: This query is probably horribly inefficient (though there is an
+            # index on (dag_id,state)). It is to deal with the case when a user
+            # clears more than max_active_runs older tasks -- we don't want the
+            # scheduler to suddenly go and start running tasks from all of the
+            # runs. (AIRFLOW-137/GH #1442)
+            #
+            # The longer term fix would be to have `clear` do this, and put DagRuns
+            # in to the queued state, then take DRs out of queued before creating
+            # any new ones
+            # TODO[HA]: Why is this on TI, not on DagRun??
+            currently_active_runs = dict(session.query(
+                TI.dag_id,
+                func.count(TI.execution_date.distinct()),
+            ).filter(
+                TI.dag_id.in_(list({dag_run.dag_id for dag_run in dag_runs})),
+                TI.state.notin_(State.finished())
+            ).group_by(TI.dag_id).all())
+
+            for dag_run in dag_runs:
+                self._schedule_dag_run(dag_run, currently_active_runs.get(dag_run.dag_id, 0), session)
+
+            guard.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to do it every time?
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.UP_FOR_RETRY],
+                    new_state=State.FAILED,
+                    session=session
+                )
+
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.QUEUED,
+                                State.SCHEDULED,
+                                State.UP_FOR_RESCHEDULE,
+                                State.SENSING],
+                    new_state=State.NONE,
+                    session=session
+                )
+
+                guard.commit()
+            except OperationalError as e:
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Lock held by another Scheduler")
+                    session.rollback()
+                else:
+                    raise
+
+            try:
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    session.rollback()
+                    return 0
+                raise
+
+            return num_queued_tis
+
+    def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            dag_hash = self.dagbag.dags_hash.get(dag.dag_id, None)
+            dag.create_dagrun(
+                run_type=DagRunType.SCHEDULED,
+                execution_date=dag_model.next_dagrun,
+                start_date=timezone.utcnow(),
+                state=State.RUNNING,
+                external_trigger=False,
+                session=session,
+                dag_hash=dag_hash
+            )
+
+        self._update_dag_next_dagruns(dag_models, session)
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _update_dag_next_dagruns(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Bulk update the next_dagrun and next_dagrun_create_after for all the dags.
+
+        We batch the select queries to get info about all the dags at once
+        """
+        # Check max_active_runs, to see if we are _now_ at the limit for any of
+        # these dag? (we've just created a DagRun for them after all)
+        active_runs_of_dags = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_([o.dag_id for o in dag_models]),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).group_by(DagRun.dag_id).all())
+
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            active_runs_of_dag = active_runs_of_dags.get(dag.dag_id, 0)
+            if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                    dag.dag_id, active_runs_of_dag, dag.max_active_runs
+                )
+                dag_model.next_dagrun_create_after = None
+            else:
+                dag_model.next_dagrun, dag_model.next_dagrun_create_after = \
+                    dag.next_dagrun_info(dag_model.next_dagrun)
+
+    def _schedule_dag_run(self, dag_run: DagRun, currently_active_runs: int, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        ``currently_active_runs`` is passed in so that a batch query can be
+        used to ask this for all dag runs in the batch, to avoid an n+1 query.
+
+        :param dag_run: The DagRun to schedule
+        :param currently_active_runs: Number of currently active runs of this DAG
+        :return: Number of tasks scheduled
+        """
+        dag = dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if (
+            dag_run.start_date and dag.dagrun_timeout and
+            dag_run.start_date < timezone.utcnow() - dag.dagrun_timeout
+        ):
+            dag_run.state = State.FAILED
+            dag_run.end_date = timezone.utcnow()
+            self.log.info("Run %s of %s has timed-out", dag_run.run_id, dag_run.dag_id)
+            session.flush()
+
+            # Work out if we should allow creating a new DagRun now?
+            self._update_dag_next_dagruns([session.query(DagModel).get(dag_run.dag_id)], session)
+
+            callback_to_execute = DagCallbackRequest(
+                full_filepath=dag.fileloc,
+                dag_id=dag.dag_id,
+                execution_date=dag_run.execution_date,
+                is_failure_callback=True,
+                msg='timed_out'
+            )
+
+            # Send SLA & DAG Success/Failure Callbacks to be executed
+            self._send_dag_callbacks_to_processor(dag_run, callback_to_execute)
+
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        if dag.max_active_runs:
+            if currently_active_runs >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s already has %d active runs, not queuing any more tasks",
+                    dag.dag_id,
+                    currently_active_runs,
+                )
+                return 0
+
+        self._verify_integrity_if_dag_changed(dag_run=dag_run, session=session)
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis, callback_to_run = dag_run.update_state(session=session, execute_callbacks=False)
+
+        self._send_dag_callbacks_to_processor(dag_run, callback_to_run)
+
+        # Get list of TIs that do not need to executed, these are
+        # tasks using DummyOperator and without on_execute_callback / on_success_callback
+        dummy_tis = [
+            ti for ti in schedulable_tis
+            if
+            (
+                ti.task.task_type == "DummyOperator"

Review comment:
       I know. For now, we can add a list of all the classes from the core that inherit from DummyOperator. This should be sufficient in most cases.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499520766



##########
File path: airflow/utils/sqlalchemy.py
##########
@@ -141,3 +142,107 @@ def skip_locked(session: Session) -> Dict[str, Any]:
         return {'skip_locked': True}
     else:
         return {}
+
+
+def nowait(session: Session) -> Dict[str, Any]:
+    """
+    Return kwargs for passing to `with_for_update()` suitable for the current DB engine version.
+
+    We do this as we document the fact that on DB engines that don't support this construct, we do not
+    support/recommend running HA scheduler. If a user ignores this and tries anyway everything will still
+    work, just slightly slower in some circumstances.
+
+    Specifically don't emit NOWAIT for MySQL < 8, or MariaDB, neither of which support this construct
+
+    See https://jira.mariadb.org/browse/MDEV-13115
+    """
+    dialect = session.bind.dialect
+
+    if dialect.name != "mysql" or dialect.supports_for_update_of:
+        return {'nowait': True}
+    else:
+        return {}
+
+
+def nulls_first(col, session: Session) -> Dict[str, Any]:
+    """
+    Adds a nullsfirst construct to the column ordering. Currently only Postgres supports it.
+    In MySQL & Sqlite NULL values are considered lower than any non-NULL value, therefore, NULL values
+    appear first when the order is ASC (ascending)
+    """
+    if session.bind.dialect.name == "postgresql":
+        return nullsfirst(col)
+    else:
+        return col
+
+
+USE_ROW_LEVEL_LOCKING: bool = conf.getboolean('scheduler', 'use_row_level_locking', fallback=True)
+
+
+def with_for_update(query, **kwargs):

Review comment:
       I think the name of this method should be changed not to be confused with th "with_for_update" which comes from the sqlachemy. It's not immediately obvious which of those are which.

##########
File path: airflow/utils/sqlalchemy.py
##########
@@ -141,3 +142,107 @@ def skip_locked(session: Session) -> Dict[str, Any]:
         return {'skip_locked': True}
     else:
         return {}
+
+
+def nowait(session: Session) -> Dict[str, Any]:
+    """
+    Return kwargs for passing to `with_for_update()` suitable for the current DB engine version.
+
+    We do this as we document the fact that on DB engines that don't support this construct, we do not
+    support/recommend running HA scheduler. If a user ignores this and tries anyway everything will still
+    work, just slightly slower in some circumstances.
+
+    Specifically don't emit NOWAIT for MySQL < 8, or MariaDB, neither of which support this construct
+
+    See https://jira.mariadb.org/browse/MDEV-13115
+    """
+    dialect = session.bind.dialect
+
+    if dialect.name != "mysql" or dialect.supports_for_update_of:
+        return {'nowait': True}
+    else:
+        return {}
+
+
+def nulls_first(col, session: Session) -> Dict[str, Any]:
+    """
+    Adds a nullsfirst construct to the column ordering. Currently only Postgres supports it.
+    In MySQL & Sqlite NULL values are considered lower than any non-NULL value, therefore, NULL values
+    appear first when the order is ASC (ascending)
+    """
+    if session.bind.dialect.name == "postgresql":
+        return nullsfirst(col)
+    else:
+        return col
+
+
+USE_ROW_LEVEL_LOCKING: bool = conf.getboolean('scheduler', 'use_row_level_locking', fallback=True)
+
+
+def with_for_update(query, **kwargs):

Review comment:
       I think the name of this method should be changed not to be confused with the "with_for_update" which comes from the sqlachemy. It's not immediately obvious which of those is which.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499557641



##########
File path: tests/www/test_views.py
##########
@@ -639,10 +638,10 @@ def test_view_uses_existing_dagbag(self, endpoint):
         self.check_content_in_response('example_bash_operator', resp)
 
     @parameterized.expand([
-        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}}'),
-        ("hello'world", r'\"conf\":{\"abc\":\"hello\\u0027world\"}}'),
-        ("<script>", r'\"conf\":{\"abc\":\"\\u003cscript\\u003e\"}}'),
-        ("\"", r'\"conf\":{\"abc\":\"\\\"\"}}'),
+        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}'),

Review comment:
       Out of curiosity - where this change came from?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil edited a comment on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
kaxil edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-736557250


   > @ashb One more question , how do we custom the number of threads ( that are in practice processes because of the GIL ) of the scheduler ?
   > 
   > there is no more max_threads in http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/latest/configurations-ref.html#scheduler
   > 
   > Thank you
   
   `max_threads` was renamed to `parsing_processes` http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/latest/configurations-ref.html#parsing-processes
   
   Note in Updating.md:
   https://github.com/apache/airflow/blob/master/UPDATING.md#scheduler-max_threads-config-has-been-renamed-to-scheduler-parsing_processes


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-735450790


   @raphaelauv That comment should be removed now -- multiple schedulers use a "mutex" (actually a lock on some DB rows) to avoid that exact problem.
   
   (Also Airflow doesn't use threads, but processes. Technicality though)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499517853



##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()
         except IntegrityError as err:
             self.log.info(str(err))
             self.log.info('Hit IntegrityError while creating the TIs for '
                           f'{dag.dag_id} - {self.execution_date}.')
             self.log.info('Doing session rollback.')
+            # TODO[HA]: We probaly need to savepoint this so we can keep the transaction alive.

Review comment:
       Any thoughs on that? I think it is a bit misleading with this name.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-692859496


   Cool. Loking at it


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494939826



##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),

Review comment:
       Yes, None in `next_dagrun_create_after` is designed to be skipped - for instance for `@once` https://github.com/apache/airflow/pull/10956/files#diff-e5cbc8f771ec50ccb79ad8505f6f5697R482-R485:
   
   ```python
   
           if (self.schedule_interval == "@once" and date_last_automated_dagrun) or \
                   self.schedule_interval is None:
               # Manual trigger, or already created the run for @once, can short circuit
               return (None, None) 
   ```
   
   or max_active_dags:
   
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499505358



##########
File path: airflow/models/dag.py
##########
@@ -1939,6 +2099,37 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs

Review comment:
       Should we remove this commend because `NUM_DAGS_PER_DAGRUN_QUERY` is configurable now?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703663101


   The CI and PROD Docker Images for the build are prepared in a separate "Build Image" workflow,
   that you will not see in the list of checks (you will see "Wait for images" jobs instead).
   
   You can checks the status of those images in [The workflow run](https://github.com/apache/airflow/actions/runs/289556504)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494942639



##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()
         except IntegrityError as err:
             self.log.info(str(err))
             self.log.info('Hit IntegrityError while creating the TIs for '
                           f'{dag.dag_id} - {self.execution_date}.')
             self.log.info('Doing session rollback.')
+            # TODO[HA]: We probaly need to savepoint this so we can keep the transaction alive.

Review comment:
       Already had that thought too :) 
   https://github.com/apache/airflow/blob/b28d67332bb052441bc2ffd00030d620aac381c8/airflow/jobs/scheduler_job.py#L1565-L1566




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494807294



##########
File path: airflow/models/dagrun.py
##########
@@ -75,6 +80,8 @@ class DagRun(Base, LoggingMixin):
         backref=backref('dag_run', uselist=False),
     )
 
+    DEFAULT_DAGRUNS_TO_EXAMINE = airflow_conf.getint('scheduler', 'max_dagruns_per_query', fallback=20)

Review comment:
       numbers picked entirely arbitrarily and it seemed to permit will in tests.
   
   The other number is hard coded still because I haven't addressed the to-do comment I already left to pull it out

##########
File path: airflow/models/dagrun.py
##########
@@ -75,6 +80,8 @@ class DagRun(Base, LoggingMixin):
         backref=backref('dag_run', uselist=False),
     )
 
+    DEFAULT_DAGRUNS_TO_EXAMINE = airflow_conf.getint('scheduler', 'max_dagruns_per_query', fallback=20)

Review comment:
       numbers picked entirely arbitrarily and it seemed to perform well in tests.
   
   The other number is hard coded still because I haven't addressed the to-do comment I already left to pull it out

##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(10).with_for_update(of=cls, **skip_locked(session=session))

Review comment:
       ```python
   		        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
   		        # doesn't try to do all the creation of dag runs
   ```

##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()

Review comment:
       Not sure yet -- https://github.com/apache/airflow/pull/10136 was where this was added only recently.

##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),

Review comment:
       Yes, None in `next_dagrun_create_after` is designed to be skipped - for instance for `@once` https://github.com/apache/airflow/pull/10956/files#diff-e5cbc8f771ec50ccb79ad8505f6f5697R482-R485:
   
   ```python
   
           if (self.schedule_interval == "@once" and date_last_automated_dagrun) or \
                   self.schedule_interval is None:
               # Manual trigger, or already created the run for @once, can short circuit
               return (None, None) 
   ```
   
   or max_active_dags:
   
   ```

##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),

Review comment:
       Yes, None in `next_dagrun_create_after` is designed to be skipped - for instance for `@once` https://github.com/apache/airflow/pull/10956/files#diff-e5cbc8f771ec50ccb79ad8505f6f5697R482-R485:
   
   ```python
   
           if (self.schedule_interval == "@once" and date_last_automated_dagrun) or \
                   self.schedule_interval is None:
               # Manual trigger, or already created the run for @once, can short circuit
               return (None, None) 
   ```
   
   or max_active_dags https://github.com/apache/airflow/pull/10956/files#diff-e5cbc8f771ec50ccb79ad8505f6f5697R1758-R1765:
   
   ```python
   
               active_runs_of_dag = num_active_runs.get(dag.dag_id, 0)
               if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
                   # Since this happens every time the dag is parsed it would be quite spammy at info
                   log.debug(
                       "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
                       dag.dag_id, active_runs_of_dag, dag.max_active_runs
                   )
                   orm_dag.next_dagrun_create_after = None
   ```

##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       Done now. all changes removed from this fie.

##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(10).with_for_update(of=cls, **skip_locked(session=session))

Review comment:
       The main reason for limiting this is two fold:
   
   1. so that when running multiple schedulers, one scheduler doesn't try to do _all_ the work of creating dag runs.
   2. when running with a single scheduler, make sure that the scheduler doesn't get "stuck" just creating dag runs instead of scheduling some tasks.

##########
File path: airflow/models/dagrun.py
##########
@@ -313,14 +360,16 @@ def update_state(self, session: Session = None) -> List[TI]:
         :rtype ready_tis: list[airflow.models.TaskInstance]
         """
 
+        start_dttm = timezone.utcnow()

Review comment:
       Already had that thought :) 
   https://github.com/apache/airflow/blob/b28d67332bb052441bc2ffd00030d620aac381c8/airflow/jobs/scheduler_job.py#L1565-L1567

##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()
         except IntegrityError as err:
             self.log.info(str(err))
             self.log.info('Hit IntegrityError while creating the TIs for '
                           f'{dag.dag_id} - {self.execution_date}.')
             self.log.info('Doing session rollback.')
+            # TODO[HA]: We probaly need to savepoint this so we can keep the transaction alive.

Review comment:
       Already had that thought too :) 
   https://github.com/apache/airflow/blob/b28d67332bb052441bc2ffd00030d620aac381c8/airflow/jobs/scheduler_job.py#L1565-L1566




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492168928



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       It didn't seem to cause any problems on 5.7 when running with just a single scheduler -- we ran some of our medium sized benchmarks and it behaved as before.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499545612



##########
File path: airflow/models/dagrun.py
##########
@@ -94,8 +103,14 @@ def __init__(
         self.conf = conf or {}
         self.state = state
         self.run_type = run_type
+        self.dag_hash = dag_hash
+        self.callback: Optional[callback_requests.DagCallbackRequest] = None

Review comment:
       Can we return the callback as a result of the update_state method rather than setting the property on the DB object? It sounds weird to add non-DB property in the DB model.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494941336



##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(10).with_for_update(of=cls, **skip_locked(session=session))

Review comment:
       The main reason for limiting this is two fold:
   
   1. so that when running multiple schedulers, one scheduler doesn't try to do _all_ the work of creating dag runs.
   2. when running with a single scheduler, make sure that the scheduler doesn't get "stuck" just creating dag runs instead of scheduling some tasks.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703755603


   And "re-running" is not happening at all - if the build image fails (like in this case transiently - on pushing to the Github registry) then it is treated as any other failure and the whole build gets cancelled


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706312266


   [The Workflow run](https://github.com/apache/airflow/actions/runs/297946414) is cancelling this PR. It has some failed jobs matching ^Pylint$,^Static checks$,^Build docs$,^Spell check docs$,^Backport packages$,^Checks: Helm tests$,^Test OpenAPI*.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-700284450


   This is the command line the tests are run with (from the logs)
   
   https://github.com/apache/airflow/pull/10956/checks?check_run_id=1178744626#step:6:279
   
   ```
   Starting the tests with those pytest arguments: --verbosity=0 --strict-markers --durations=100 --cov=airflow/ --cov-config=.coveragerc --cov-report=xml:/files/coverage.xml --color=yes --maxfail=50 --pythonwarnings=ignore::DeprecationWarning --pythonwarnings=ignore::PendingDeprecationWarning --junitxml=/files/test_result.xml --setup-timeout=10 --execution-timeout=30 --teardown-timeout=10 tests
   ````
   
   
   


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500543151



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       Finally found time to do some testing, on my local laptop running against this PR, here is the code I've been testing with:
   
   ```
       for count in range(repeat):
           with db.create_session() as session:
               dagrun = session.query(DR).filter(DR.dag_id == dag.dag_id).first()
               dagrun.dag = dag
               start = time.perf_counter()
   
               dagrun.update_state(session=session)
               times.append(time.perf_counter() - start)
           print("Run %d time: %.5f" % (count + 1, times[-1]))
   
           if count + 1 != repeat:
               with db.create_session() as session:
                   reset_dag(dag, session)
   
               create_dag_runs(dag, num_runs, session)
   
   ```
   
   (`reset_dag` deletes everything from TI and DR tables, `create_dag_runs` does what it says, creates 1 (or more) runs, just to add more rows to the TI table.)
   
   And the numbers I got were:
   
   ```
   Run 1 time: 2.80744
   Run 2 time: 3.07741
   Run 3 time: 6.30900
   Run 4 time: 6.34341
   Run 5 time: 6.56565
   
   
   Time for 5 dag runs of 1 dags with 21407 total tasks: 5.0206s (±1.902s)
   ```
   
   Before #11147 it was massively _much_ more variable:
   
   ```
   Run 1 time: 11.21811
   Run 2 time: 142.50100
   Run 3 time: 16.76023
   Run 4 time: 151.12660
   Run 5 time: 161.86329
   
   
   Time for 5 dag runs of 1 dags with 21407 total tasks: 96.6938s (±75.835s)
   ```
   
   And on 1.10.12 (with a bit of a change in the benchmark code to check the TI deps too (it turns out udpate_state didn't used to do schedule TIs -- that was only added in #4751) is... slow. I'll update this comment with timing when it actually finishes.7 minutes so far and it hasn't completed a single iteration.
   
   @KevinYang21 I think this makes this approach _more_ than fast enough!




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501638947



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       Will do




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499552738



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:
+                self.log.info(
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
+                )
+                break
             if self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested DAG parse count (%d) has been reached after %d "
+                    " scheduler loops",
+                    self.num_times_parse_dags, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        # Put a check in place to make sure we don't commit unexpectedly
+        with prohibit_commit(session) as guard:
+
+            query = DagModel.dags_needing_dagruns(session)
+            self._create_dag_runs(query.all(), session)
+
+            # commit the session - Release the write lock on DagModel table.
+            guard.commit()
+            # END: create dagruns
+
+            dag_runs = DagRun.next_dagruns_to_examine(session)
+
+            # Bulk fetch the currently active dag runs for the dags we are
+            # examining, rather than making one query per DagRun
+
+            # TODO: This query is probably horribly inefficient (though there is an
+            # index on (dag_id,state)). It is to deal with the case when a user
+            # clears more than max_active_runs older tasks -- we don't want the
+            # scheduler to suddenly go and start running tasks from all of the
+            # runs. (AIRFLOW-137/GH #1442)
+            #
+            # The longer term fix would be to have `clear` do this, and put DagRuns
+            # in to the queued state, then take DRs out of queued before creating
+            # any new ones
+            # TODO[HA]: Why is this on TI, not on DagRun??
+            currently_active_runs = dict(session.query(
+                TI.dag_id,
+                func.count(TI.execution_date.distinct()),
+            ).filter(
+                TI.dag_id.in_(list({dag_run.dag_id for dag_run in dag_runs})),
+                TI.state.notin_(State.finished())
+            ).group_by(TI.dag_id).all())
+
+            for dag_run in dag_runs:
+                self._schedule_dag_run(dag_run, currently_active_runs.get(dag_run.dag_id, 0), session)
+
+            guard.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    session.rollback()
+                    return 0
+                raise
+
+            return num_queued_tis
+
+    def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            dag_hash = self.dagbag.dags_hash.get(dag.dag_id, None)
+            dag.create_dagrun(
+                run_type=DagRunType.SCHEDULED,
+                execution_date=dag_model.next_dagrun,
+                start_date=timezone.utcnow(),
+                state=State.RUNNING,
+                external_trigger=False,
+                session=session,
+                dag_hash=dag_hash
+            )
+
+        self._update_dag_next_dagruns(dag_models, session)
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _update_dag_next_dagruns(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Bulk update the next_dagrun and next_dagrun_create_after for all the dags.
+
+        We batch the select queries to get info about all the dags at once
+        """
+        # Check max_active_runs, to see if we are _now_ at the limit for any of
+        # these dag? (we've just created a DagRun for them after all)
+        active_runs_of_dags = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_([o.dag_id for o in dag_models]),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).group_by(DagRun.dag_id).all())
+
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            active_runs_of_dag = active_runs_of_dags.get(dag.dag_id, 0)
+            if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                    dag.dag_id, active_runs_of_dag, dag.max_active_runs
+                )
+                dag_model.next_dagrun_create_after = None
+            else:
+                dag_model.next_dagrun, dag_model.next_dagrun_create_after = \
+                    dag.next_dagrun_info(dag_model.next_dagrun)
+
+    def _schedule_dag_run(self, dag_run: DagRun, currently_active_runs: int, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        ``currently_active_runs`` is passed in so that a batch query can be
+        used to ask this for all dag runs in the batch, to avoid an n+1 query.
+
+        :param dag_run: The DagRun to schedule
+        :param currently_active_runs: Number of currently active runs of this DAG
+        :return: Number of tasks scheduled
+        """
+        dag = dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if (
+            dag_run.start_date and dag.dagrun_timeout and
+            dag_run.start_date < timezone.utcnow() - dag.dagrun_timeout
+        ):
+            dag_run.state = State.FAILED
+            dag_run.end_date = timezone.utcnow()
+            self.log.info("Run %s of %s has timed-out", dag_run.run_id, dag_run.dag_id)
+            session.flush()
+
+            # Work out if we should allow creating a new DagRun now?
+            self._update_dag_next_dagruns([session.query(DagModel).get(dag_run.dag_id)], session)
+
+            dag_run.callback = DagCallbackRequest(
+                full_filepath=dag.fileloc,
+                dag_id=dag.dag_id,
+                execution_date=dag_run.execution_date,
+                is_failure_callback=True,
+                msg='timed_out'
+            )
+
+            # Send SLA & DAG Success/Failure Callbacks to be executed
+            self._send_dag_callbacks_to_processor(dag_run)
+
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        if dag.max_active_runs:
+            if currently_active_runs >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s already has %d active runs, not queuing any more tasks",
+                    dag.dag_id,
+                    currently_active_runs,
+                )
+                return 0
+
+        self._verify_integrity_if_dag_changed(dag_run=dag_run, session=session)
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session, execute_callbacks=False)
+        # TODO[HA]: Don't return, update these from in update_state?
+
+        # Get list of TIs that do not need to executed, these are
+        # tasks using DummyOperator and without on_execute_callback / on_success_callback
+        dummy_tis = [
+            ti for ti in schedulable_tis
+            if
+            (
+                ti.task.task_type == "DummyOperator"
+                and not ti.task.on_execute_callback
+                and not ti.task.on_success_callback
+            )
+        ]
+
+        # This will do one query per dag run. We "could" build up a complex
+        # query to update all the TIs across all the execution dates and dag
+        # IDs in a single query, but it turns out that can be _very very slow_
+        # see #11147/commit ee90807ac for more details
+        count = session.query(TI).filter(
+            TI.dag_id == dag_run.dag_id,
+            TI.execution_date == dag_run.execution_date,
+            TI.task_id.in_(ti.task_id for ti in schedulable_tis if ti not in dummy_tis)
+        ).update({TI.state: State.SCHEDULED}, synchronize_session=False)
+
+        # Tasks using DummyOperator should not be executed, mark them as success
+        if dummy_tis:
+            session.query(TI).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.execution_date == dag_run.execution_date,
+                TI.task_id.in_(ti.task_id for ti in dummy_tis)
+            ).update({
+                TI.state: State.SUCCESS,
+                TI.start_date: timezone.utcnow(),
+                TI.end_date: timezone.utcnow(),
+                TI.duration: 0
+            }, synchronize_session=False)
+
+        return count
+
+    @provide_session
+    def _verify_integrity_if_dag_changed(self, dag_run: DagRun, session=None):
+        """Only run DagRun.verify integrity if Serialized DAG has changed since it is slow"""
+        latest_version = SerializedDagModel.get_latest_version_hash(dag_run.dag_id, session=session)
+        if dag_run.dag_hash == latest_version:
+            self.log.debug("DAG %s not changed structure, skipping dagrun.verify_integrity", dag_run.dag_id)
+            return
+
+        dag_run.dag_hash = latest_version
+
+        # Refresh the DAG
+        dag_run.dag = self.dagbag.get_dag(dag_id=dag_run.dag_id, session=session)
+
+        # Verify integrity also takes care of session.flush
+        dag_run.verify_integrity(session=session)
+
+    def _send_dag_callbacks_to_processor(self, dag_run: DagRun):
+        if not self.processor_agent:
+            raise ValueError("Processor agent is not started.")
+
+        dag = dag_run.get_dag()
+        self._manage_slas(dag)
+        if dag_run.callback:
+            self.processor_agent.send_callback_to_execute(dag_run.callback)
+
+    def _manage_slas(self, dag: DAG):

Review comment:
       Is this name still correct? It seems to me that its content changed drastically while the name remained without drastic change.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-699455633


   For anyone review by this, the code is pretty feature complete now - there are only a few unit tests left to fix up due to the changed code.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494938864



##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()

Review comment:
       Not sure yet -- https://github.com/apache/airflow/pull/10136 was where this was added only recently.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r498462855



##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(10).with_for_update(of=cls, **skip_locked(session=session))

Review comment:
       Changed to tunable in https://github.com/apache/airflow/pull/10956/commits/ef9101ff910eba85a2782f894f0e9dfbafc04689




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492188003



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       I see. I still have to wrap my head around the locking consequences here. I understand that here the only locked tables will be TI and DR. the DM is "selectinload"  so likely not locked.
   
   I really just want to understand the consequences and risks. I think a the end we should come up with some "cautious" recommendations to the users. After looking at the potential issues and gains, my current feeling (but needs a bit deeper thinking and testing) is that 
   
   * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you're adventurous, but expect moderate gains and higher risks of concurrency related problems
   * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems. 
   
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499532425



##########
File path: airflow/utils/sqlalchemy.py
##########
@@ -141,3 +142,107 @@ def skip_locked(session: Session) -> Dict[str, Any]:
         return {'skip_locked': True}
     else:
         return {}
+
+
+def nowait(session: Session) -> Dict[str, Any]:
+    """
+    Return kwargs for passing to `with_for_update()` suitable for the current DB engine version.
+
+    We do this as we document the fact that on DB engines that don't support this construct, we do not
+    support/recommend running HA scheduler. If a user ignores this and tries anyway everything will still
+    work, just slightly slower in some circumstances.
+
+    Specifically don't emit NOWAIT for MySQL < 8, or MariaDB, neither of which support this construct
+
+    See https://jira.mariadb.org/browse/MDEV-13115
+    """
+    dialect = session.bind.dialect
+
+    if dialect.name != "mysql" or dialect.supports_for_update_of:
+        return {'nowait': True}
+    else:
+        return {}
+
+
+def nulls_first(col, session: Session) -> Dict[str, Any]:
+    """
+    Adds a nullsfirst construct to the column ordering. Currently only Postgres supports it.
+    In MySQL & Sqlite NULL values are considered lower than any non-NULL value, therefore, NULL values
+    appear first when the order is ASC (ascending)
+    """
+    if session.bind.dialect.name == "postgresql":
+        return nullsfirst(col)
+    else:
+        return col
+
+
+USE_ROW_LEVEL_LOCKING: bool = conf.getboolean('scheduler', 'use_row_level_locking', fallback=True)
+
+
+def with_for_update(query, **kwargs):

Review comment:
       I named it the same on purpose, as it mirrors the underlying method, but I see your point
   
   How about `with_row_locks`?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703747520


   @potiuk Something might be off about the cancelling? -- it's cancelled the job, but nothing has re-run it yet.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499644812



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:

Review comment:
       I am fine with both :)




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499531994



##########
File path: airflow/executors/celery_executor.py
##########
@@ -225,7 +225,15 @@ def _send_tasks_to_celery(self, task_tuples_to_send):
         # since tasks are roughly uniform in size
         chunksize = self._num_tasks_per_send_process(len(task_tuples_to_send))
         num_processes = min(len(task_tuples_to_send), self._sync_parallelism)
-        with Pool(processes=num_processes) as send_pool:
+
+        def reset_signals():
+            # Since we are run from inside the SchedulerJob, we don't to
+            # inherit the signal handlers that we registered there.
+            import signal
+            signal.signal(signal.SIGINT, signal.SIG_DFL)
+            signal.signal(signal.SIGTERM, signal.SIG_DFL)
+
+        with Pool(processes=num_processes, initializer=reset_signals) as send_pool:

Review comment:
       Probably yeah. I've never hit it in any other version _that I know of_, but hit it quite frequently when running in >=2 schedulers, so something about this PR made it happen with some regularity.
   
   It's already it's own commit (https://github.com/apache/airflow/pull/10956/commits/1752c1e90fb82e972ae4a608dc8daff500ac67e7) so yeah, I'll pull this out to its own PR. I wonder if this happens to be the cause of some of the long-standing "scheduler is alive, but not scheduling anything anymore" bugs.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706211402


   [The Workflow run](https://github.com/apache/airflow/actions/runs/297640662) is cancelling this PR. It has some failed jobs matching ^Pylint$,^Static checks$,^Build docs$,^Spell check docs$,^Backport packages$,^Checks: Helm tests$,^Test OpenAPI*.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500572553



##########
File path: airflow/models/dagbag.py
##########
@@ -510,6 +513,6 @@ def sync_to_db(self):
         DAG.bulk_sync_to_db(self.dags.values())
         # Write Serialized DAGs to DB if DAG Serialization is turned on
         # Even though self.read_dags_from_db is False
-        if settings.STORE_SERIALIZED_DAGS:
+        if settings.STORE_SERIALIZED_DAGS or self.read_dags_from_db:

Review comment:
       This change was a bit of a hack here, and we'll tidy it up.
   
   Since the scheduler now requires DAG serialization to operate, we need a way for dag bags to Load dags from given files only, and not from the DB, but then also a way to make them _write_ things back to the DB.
   
   We'll pull this out in to a separate PR, essentially removing the `STORE_SERIALIZED_DAGS` option entirely, and then this bulk_sync_to_db can then just always write to the DB.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492194552



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       Or even `DagDbProxy` - it even can be used by DagBag by composition when needed?
   
   Seems That DagBag(read_dags_from_db=False) is really used for this: `A dagbag is a collection of dags, parsed out of a folder tree` (from the docstring). Then "DagBag(read_dags_from_db=True) is rather used as a proxy to retrieve Dags from teh DB only `get me the DAG with this id from the DB no matter in which folder it is`. 
   
   Sounds like DagBag could use the DagDbProxy when needed and all the places where we create DagBag(read_dags_from_db=True) we could use directly the proxy. That seems to better fit the single-responsibility principle. 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499498291



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1714,53 +1321,158 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to

Review comment:
       I agree that it would be nice to point users to information how it can be changed 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] pingzh commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
pingzh commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502720900



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       These are some numbers after we cherry picked changes of #4751, (#11010 for 1.10 branch) and #7503
   
   ### before AIRFLOW-3607: Process a new dag run
   
   ```
   [** REMOTE di-airflow-bronze-scheduler **]ping_zhang@i-0497283d24627a6ce:~/test-AIRFLOW-3607
   $ tail -f log.txt
   2020-10-09 21:52:18,144  Load DagBag: 87.1108751297 seconds
   2020-10-09 21:52:42,324 Examining DAG run <DagRun minerva_compute @ 2020-10-09 21:52:18.238537+00:00: scheduled__2020-10-09T21:52:18.238537+00:00, externally triggered: False>
   2020-10-09 21:54:20,709 Verify Integrity in 98.3845481873 seconds
   2020-10-09 21:54:24,393 Update State in 3.68303990364 seconds
   2020-10-09 21:56:34,579 Deps Check in 126.738894939 seconds
   2020-10-09 21:56:34,579 process_tasks in 232.254889965 seconds with ready tis: 956
   ```
   
   ### after AIRFLOW-3607: : Process a new dag run 
   
   ```
   2020-10-09 22:52:29,656 Load DagBag: 86.3233180046 seconds
   2020-10-09 22:52:54,967 Examining DAG run <DagRun minerva_compute @ 2020-10-09 22:52:29.742831+00:00: scheduled__2020-10-09T22:52:29.742831+00:00, externally triggered: False>
   2020-10-09 22:54:33,285 Verify Integrity in 98.3177959919 seconds
   2020-10-09 22:56:27,847 Update State in 114.560956001 seconds
   2020-10-09 22:56:27,854 process_tasks in 212.88758111 seconds ready tis: 956
   ```
   ----
   
   ### before AIRFLOW-3607: Process an existing  dag run with half root tasks in `success` state
   ```
   2020-10-09 22:38:29,420 Load DagBag: 86.8423230648 seconds
   2020-10-09 22:43:13,357 Examining DAG run <DagRun minerva_compute @ 2020-08-28 00:00:00+00:00: scheduled__2020-08-28T00:00:00+00:00, externally triggered: False>
   2020-10-09 22:43:25,453 Verify Integrity in 12.0952570438 seconds
   2020-10-09 22:43:29,027 Update State in 3.57410883904 seconds
   2020-10-09 22:44:53,102 Deps Check perf in 83.3023910522 seconds
   2020-10-09 22:44:53,102 process_tasks in 99.7442808151 seconds ready tis: 651
   ```
   
   ### after AIRFLOW-3607: Process an existing dag run with half root tasks in `success` state
   ```
   2020-10-09 23:01:33,544 Load DagBag: 88.0396211147 seconds
   2020-10-09 23:06:30,308 Examining DAG run <DagRun minerva_compute @ 2020-08-28 00:00:00+00:00: scheduled__2020-08-28T00:00:00+00:00, externally triggered: False>
   2020-10-09 23:06:42,825 Verify Integrity in 12.516479969 seconds
   2020-10-09 23:08:00,063 Update State in 77.2370829582 seconds
   2020-10-09 23:08:00,066 process_tasks in 89.7578499317 seconds ready tis: 651
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499513837



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       @KevinYang21 -> do you think we need more elaboration in this part? Or are you ok with this now? 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494939826



##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),

Review comment:
       Yes, None in `next_dagrun_create_after` is designed to be skipped - for instance for `@once` https://github.com/apache/airflow/pull/10956/files#diff-e5cbc8f771ec50ccb79ad8505f6f5697R482-R485:
   
   ```python
   
           if (self.schedule_interval == "@once" and date_last_automated_dagrun) or \
                   self.schedule_interval is None:
               # Manual trigger, or already created the run for @once, can short circuit
               return (None, None) 
   ```
   
   or max_active_dags https://github.com/apache/airflow/pull/10956/files#diff-e5cbc8f771ec50ccb79ad8505f6f5697R1758-R1765:
   
   ```python
   
               active_runs_of_dag = num_active_runs.get(dag.dag_id, 0)
               if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
                   # Since this happens every time the dag is parsed it would be quite spammy at info
                   log.debug(
                       "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
                       dag.dag_id, active_runs_of_dag, dag.max_active_runs
                   )
                   orm_dag.next_dagrun_create_after = None
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494940402



##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       Done now. all changes removed from this fie.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500606943



##########
File path: airflow/config_templates/config.yml
##########
@@ -1562,6 +1562,41 @@
       type: string
       example: ~
       default: "512"
+    - name: use_row_level_locking
+      description: |
+        Should the scheduler issue `SELECT ... FOR UPDATE` in relevant queries.
+        If this is set to False then you should not run more than a single
+        scheduler at once
+      version_added: 2.0.0
+      type: boolean
+      example: ~
+      default: "True"
+    - name: max_dagruns_to_create_per_loop
+      description: |
+        This changes the number of dags that are locked by each scheduler when
+        creating dag runs. One possible reason for setting this lower is if you
+        have huge dags and are running multiple schedules, you won't want one
+        scheduler to do all the work.
+
+        Default: 10
+      example: ~
+      version_added: 2.0.0
+      type: string
+      default: ~
+    - name: max_dagruns_per_loop_to_schedule
+      description: |
+        How many DagRuns should a scheduler exaimne (and lock) when scheduling

Review comment:
       ```suggestion
           How many DagRuns should a scheduler examine (and lock) when scheduling
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500590276



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       We can defer the code split/refactor to later. Will address other comments there.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502501656



##########
File path: tests/jobs/test_backfill_job.py
##########
@@ -160,10 +160,11 @@ def test_trigger_controller_dag(self):
         )
         job.run()
 
-        task_instances_list = dag_file_processor._process_task_instances(
-            target_dag,
-            dag_runs=DagRun.find(dag_id='example_trigger_target_dag')
-        )
+        task_instances_list = []

Review comment:
       I don't see change. Can you check it?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499527888



##########
File path: tests/jobs/test_backfill_job.py
##########
@@ -160,10 +160,11 @@ def test_trigger_controller_dag(self):
         )
         job.run()
 
-        task_instances_list = dag_file_processor._process_task_instances(
-            target_dag,
-            dag_runs=DagRun.find(dag_id='example_trigger_target_dag')
-        )
+        task_instances_list = []

Review comment:
       Is it necessary?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500607262



##########
File path: airflow/config_templates/config.yml
##########
@@ -1562,6 +1562,41 @@
       type: string
       example: ~
       default: "512"
+    - name: use_row_level_locking
+      description: |
+        Should the scheduler issue `SELECT ... FOR UPDATE` in relevant queries.
+        If this is set to False then you should not run more than a single
+        scheduler at once
+      version_added: 2.0.0
+      type: boolean
+      example: ~
+      default: "True"
+    - name: max_dagruns_to_create_per_loop
+      description: |
+        This changes the number of dags that are locked by each scheduler when
+        creating dag runs. One possible reason for setting this lower is if you
+        have huge dags and are running multiple schedules, you won't want one
+        scheduler to do all the work.
+
+        Default: 10
+      example: ~
+      version_added: 2.0.0
+      type: string
+      default: ~
+    - name: max_dagruns_per_loop_to_schedule
+      description: |
+        How many DagRuns should a scheduler exaimne (and lock) when scheduling
+        and queuing tasks. Increasing this limit will allow more throughput for
+        smaller DAGs but will likely slow down throughput for larger (>500
+        tasks for example.) DAGs. Setting this to high when using multiple

Review comment:
       ```suggestion
           tasks for example) DAGs. Setting this too high when using multiple
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500612867



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       how about `bulk_update_db`? I generally prefer shorter names 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499574149



##########
File path: tests/www/test_views.py
##########
@@ -639,10 +638,10 @@ def test_view_uses_existing_dagbag(self, endpoint):
         self.check_content_in_response('example_bash_operator', resp)
 
     @parameterized.expand([
-        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}}'),
-        ("hello'world", r'\"conf\":{\"abc\":\"hello\\u0027world\"}}'),
-        ("<script>", r'\"conf\":{\"abc\":\"\\u003cscript\\u003e\"}}'),
-        ("\"", r'\"conf\":{\"abc\":\"\\\"\"}}'),
+        ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}'),

Review comment:
       Extra params now appear in the output, so the closing `}` is now a `,`.
   
   The extra params that show up are the two new date fields I added to the model, as we use `sqlalchemy_to_dict` here so we get all the columns showing up in the JSON.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501914789



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -567,302 +567,71 @@ def update_import_errors(session: Session, dagbag: DagBag) -> None:
                 stacktrace=stacktrace))
         session.commit()
 
-    # pylint: disable=too-many-return-statements,too-many-branches
     @provide_session
-    def create_dag_run(
-        self,
-        dag: DAG,
-        dag_runs: Optional[List[DagRun]] = None,
-        session: Session = None,
-    ) -> Optional[DagRun]:
-        """
-        This method checks whether a new DagRun needs to be created
-        for a DAG based on scheduling interval.
-        Returns DagRun if one is scheduled. Otherwise returns None.
-        """
-        # pylint: disable=too-many-nested-blocks
-        if not dag.schedule_interval:
-            return None
-
-        active_runs: List[DagRun]
-        if dag_runs is None:
-            active_runs = DagRun.find(
-                dag_id=dag.dag_id,
-                state=State.RUNNING,
-                external_trigger=False,
-                session=session
-            )
-        else:
-            active_runs = [
-                dag_run
-                for dag_run in dag_runs
-                if not dag_run.external_trigger
-            ]
-        # return if already reached maximum active runs and no timeout setting
-        if len(active_runs) >= dag.max_active_runs and not dag.dagrun_timeout:
-            return None
-        timed_out_runs = 0
-        for dr in active_runs:
-            if (
-                dr.start_date and dag.dagrun_timeout and
-                dr.start_date < timezone.utcnow() - dag.dagrun_timeout
-            ):
-                dr.state = State.FAILED
-                dr.end_date = timezone.utcnow()
-                dag.handle_callback(dr, success=False, reason='dagrun_timeout',
-                                    session=session)
-                timed_out_runs += 1
-        session.commit()
-        if len(active_runs) - timed_out_runs >= dag.max_active_runs:
-            return None
-
-        # this query should be replaced by find dagrun
-        last_scheduled_run: Optional[datetime.datetime] = (
-            session.query(func.max(DagRun.execution_date))
-            .filter_by(dag_id=dag.dag_id)
-            .filter(or_(
-                DagRun.external_trigger == False,  # noqa: E712 pylint: disable=singleton-comparison
-                DagRun.run_type == DagRunType.SCHEDULED.value
-            )).scalar()
-        )
-
-        # don't schedule @once again
-        if dag.schedule_interval == '@once' and last_scheduled_run:
-            return None
-
-        # don't do scheduler catchup for dag's that don't have dag.catchup = True
-        if not (dag.catchup or dag.schedule_interval == '@once'):
-            # The logic is that we move start_date up until
-            # one period before, so that timezone.utcnow() is AFTER
-            # the period end, and the job can be created...
-            now = timezone.utcnow()
-            next_start = dag.following_schedule(now)
-            last_start = dag.previous_schedule(now)
-            if next_start <= now or isinstance(dag.schedule_interval, timedelta):
-                new_start = last_start
-            else:
-                new_start = dag.previous_schedule(last_start)
-
-            if dag.start_date:
-                if new_start >= dag.start_date:
-                    dag.start_date = new_start
-            else:
-                dag.start_date = new_start
-
-        next_run_date = None
-        if not last_scheduled_run:
-            # First run
-            task_start_dates = [t.start_date for t in dag.tasks]
-            if task_start_dates:
-                next_run_date = dag.normalize_schedule(min(task_start_dates))
-                self.log.debug(
-                    "Next run date based on tasks %s",
-                    next_run_date
-                )
-        else:
-            next_run_date = dag.following_schedule(last_scheduled_run)
-
-        # make sure backfills are also considered
-        last_run = dag.get_last_dagrun(session=session)
-        if last_run and next_run_date:
-            while next_run_date <= last_run.execution_date:
-                next_run_date = dag.following_schedule(next_run_date)
-
-        # don't ever schedule prior to the dag's start_date
-        if dag.start_date:
-            next_run_date = (dag.start_date if not next_run_date
-                             else max(next_run_date, dag.start_date))
-            if next_run_date == dag.start_date:
-                next_run_date = dag.normalize_schedule(dag.start_date)
-
-            self.log.debug(
-                "Dag start date: %s. Next run date: %s",
-                dag.start_date, next_run_date
-            )
-
-        # don't ever schedule in the future or if next_run_date is None
-        if not next_run_date or next_run_date > timezone.utcnow():
-            return None
-
-        # this structure is necessary to avoid a TypeError from concatenating
-        # NoneType
-        period_end = None
-        if dag.schedule_interval == '@once':
-            period_end = next_run_date
-        elif next_run_date:
-            period_end = dag.following_schedule(next_run_date)
-
-        # Don't schedule a dag beyond its end_date (as specified by the dag param)
-        if next_run_date and dag.end_date and next_run_date > dag.end_date:
-            return None
-
-        # Don't schedule a dag beyond its end_date (as specified by the task params)
-        # Get the min task end date, which may come from the dag.default_args
-        min_task_end_date = min([t.end_date for t in dag.tasks if t.end_date], default=None)
-        if next_run_date and min_task_end_date and next_run_date > min_task_end_date:
-            return None
-
-        if next_run_date and period_end and period_end <= timezone.utcnow():
-            next_run = dag.create_dagrun(
-                run_type=DagRunType.SCHEDULED,
-                execution_date=next_run_date,
-                start_date=timezone.utcnow(),
-                state=State.RUNNING,
-                external_trigger=False
-            )
-            return next_run
-
-        return None
-
-    @provide_session
-    def _process_task_instances(
-        self, dag: DAG, dag_runs: List[DagRun], session: Session = None
-    ) -> List[TaskInstanceKey]:
-        """
-        This method schedules the tasks for a single DAG by looking at the
-        active DAG runs and adding task instances that should run to the
-        queue.
-        """
-        # update the state of the previously active dag runs
-        active_dag_runs = 0
-        task_instances_list = []
-        for run in dag_runs:
-            self.log.info("Examining DAG run %s", run)
-            # don't consider runs that are executed in the future unless
-            # specified by config and schedule_interval is None
-            if run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
-                self.log.error(
-                    "Execution date is in future: %s",
-                    run.execution_date
-                )
-                continue
-
-            if active_dag_runs >= dag.max_active_runs:
-                self.log.info("Number of active dag runs reached max_active_run.")
-                break
-
-            # skip backfill dagruns for now as long as they are not really scheduled
-            if run.is_backfill:
-                continue
-
-            # todo: run.dag is transient but needs to be set
-            run.dag = dag  # type: ignore
-            # todo: preferably the integrity check happens at dag collection time
-            run.verify_integrity(session=session)
-            ready_tis = run.update_state(session=session)
-            if run.state == State.RUNNING:
-                active_dag_runs += 1
-                self.log.debug("Examining active DAG run: %s", run)
-                for ti in ready_tis:
-                    self.log.debug('Queuing task: %s', ti)
-                    task_instances_list.append(ti.key)
-        return task_instances_list
-
-    @provide_session
-    def _process_dags(self, dags: List[DAG], session: Session = None) -> List[TaskInstanceKey]:
-        """
-        Iterates over the dags and processes them. Processing includes:
-
-        1. Create appropriate DagRun(s) in the DB.
-        2. Create appropriate TaskInstance(s) in the DB.
-        3. Send emails for tasks that have missed SLAs (if CHECK_SLAS config enabled).
-
-        :param dags: the DAGs from the DagBag to process
-        :type dags: List[airflow.models.DAG]
-        :rtype: list[TaskInstance]
-        :return: A list of generated TaskInstance objects
-        """
-        check_slas: bool = conf.getboolean('core', 'CHECK_SLAS', fallback=True)
-        use_job_schedule: bool = conf.getboolean('scheduler', 'USE_JOB_SCHEDULE')
-
-        # pylint: disable=too-many-nested-blocks
-        tis_out: List[TaskInstanceKey] = []
-        dag_ids: List[str] = [dag.dag_id for dag in dags]
-        dag_runs = DagRun.find(dag_id=dag_ids, state=State.RUNNING, session=session)
-        # As per the docs of groupby (https://docs.python.org/3/library/itertools.html#itertools.groupby)
-        # we need to use `list()` otherwise the result will be wrong/incomplete
-        dag_runs_by_dag_id: Dict[str, List[DagRun]] = {
-            k: list(v) for k, v in groupby(dag_runs, lambda d: d.dag_id)
-        }
-
-        for dag in dags:
-            dag_id: str = dag.dag_id
-            self.log.info("Processing %s", dag_id)
-            dag_runs_for_dag = dag_runs_by_dag_id.get(dag_id) or []
-
-            # Only creates DagRun for DAGs that are not subdag since
-            # DagRun of subdags are created when SubDagOperator executes.
-            if not dag.is_subdag and use_job_schedule:
-                dag_run = self.create_dag_run(dag, dag_runs=dag_runs_for_dag)
-                if dag_run:
-                    dag_runs_for_dag.append(dag_run)
-                    expected_start_date = dag.following_schedule(dag_run.execution_date)
-                    if expected_start_date:
-                        schedule_delay = dag_run.start_date - expected_start_date
-                        Stats.timing(
-                            'dagrun.schedule_delay.{dag_id}'.format(dag_id=dag.dag_id),
-                            schedule_delay)
-                    self.log.info("Created %s", dag_run)
-
-            if dag_runs_for_dag:
-                tis_out.extend(self._process_task_instances(dag, dag_runs_for_dag))
-                if check_slas:
-                    self.manage_slas(dag)
-
-        return tis_out
-
-    def _find_dags_to_process(self, dags: List[DAG]) -> List[DAG]:
-        """
-        Find the DAGs that are not paused to process.
-
-        :param dags: specified DAGs
-        :return: DAGs to process
-        """
-        if self.dag_ids:
-            dags = [dag for dag in dags
-                    if dag.dag_id in self.dag_ids]
-        return dags
-
-    @provide_session
-    def execute_on_failure_callbacks(
+    def execute_callbacks(
         self,
         dagbag: DagBag,
-        failure_callback_requests: List[FailureCallbackRequest],
+        callback_requests: List[CallbackRequest],
         session: Session = None
     ) -> None:
         """
         Execute on failure callbacks. These objects can come from SchedulerJob or from
         DagFileProcessorManager.
 
-        :param failure_callback_requests: failure callbacks to execute
-        :type failure_callback_requests: List[airflow.utils.dag_processing.FailureCallbackRequest]
+        :param dagbag: Dag Bag of dags
+        :param callback_requests: failure callbacks to execute
+        :type callback_requests: List[airflow.utils.callback_requests.CallbackRequest]
         :param session: DB session.
         """
-        for request in failure_callback_requests:
-            simple_ti = request.simple_task_instance
-            if simple_ti.dag_id in dagbag.dags:
-                dag = dagbag.dags[simple_ti.dag_id]
-                if simple_ti.task_id in dag.task_ids:
-                    task = dag.get_task(simple_ti.task_id)
-                    ti = TI(task, simple_ti.execution_date)
-                    # Get properties needed for failure handling from SimpleTaskInstance.
-                    ti.start_date = simple_ti.start_date
-                    ti.end_date = simple_ti.end_date
-                    ti.try_number = simple_ti.try_number
-                    ti.state = simple_ti.state
-                    ti.test_mode = self.UNIT_TEST_MODE
+        for request in callback_requests:
+            try:
+                if isinstance(request, TaskCallbackRequest):
+                    self._execute_task_callbacks(dagbag, request)
+                elif isinstance(request, SlaCallbackRequest):
+                    self.manage_slas(dagbag.dags.get(request.dag_id))
+                elif isinstance(request, DagCallbackRequest):
+                    self._execute_dag_callbacks(dagbag, request, session)
+            except Exception:  # pylint: disable=broad-except
+                self.log.exception("Error executing callback for File: %s", request.full_filepath)

Review comment:
       Will do




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489347417



##########
File path: airflow/models/dagbag.py
##########
@@ -510,6 +513,6 @@ def sync_to_db(self):
         DAG.bulk_sync_to_db(self.dags.values())
         # Write Serialized DAGs to DB if DAG Serialization is turned on
         # Even though self.read_dags_from_db is False
-        if settings.STORE_SERIALIZED_DAGS:
+        if settings.STORE_SERIALIZED_DAGS or self.read_dags_from_db:

Review comment:
       Can you tell a little more about it? How do you want serialization of the same object to a database to produce different results?  Is it by adding the `next_dagrun`, `next_dagrun_create_after` fields to the DAG in the sync_to_db method?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499833303



##########
File path: airflow/models/dagrun.py
##########
@@ -313,14 +360,16 @@ def update_state(self, session: Session = None) -> List[TI]:
         :rtype ready_tis: list[airflow.models.TaskInstance]
         """
 
+        start_dttm = timezone.utcnow()

Review comment:
       Defer to later I think -- not changed in name or behaviour in this 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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499833094



##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()
         except IntegrityError as err:
             self.log.info(str(err))
             self.log.info('Hit IntegrityError while creating the TIs for '
                           f'{dag.dag_id} - {self.execution_date}.')
             self.log.info('Doing session rollback.')
+            # TODO[HA]: We probaly need to savepoint this so we can keep the transaction alive.

Review comment:
       Deferring this -- the behaviour or name of this function hasn't changed in this 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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502492775



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1749,62 +1403,353 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if loop_count >= self.num_runs > 0:
+                self.log.info(
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
+                )
+                break
             if self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested DAG parse count (%d) has been reached after %d "
+                    " scheduler loops",
+                    self.num_times_parse_dags, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+          Since creating Dag Runs is a relatively time consuming process, we select only 10 dags by default
+          (configurable via ``scheduler.max_dagruns_to_create_per_loop`` setting) - putting this higher will
+          mean one scheduler could spend a chunk of time creating dag runs, and not ever get around to
+          scheduling tasks.
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default, configurable
+          via ``scheduler.max_dagruns_per_loop_to_schedule`` config setting) and tries to progress state (TIs
+          to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+          The reason we don't select all dagruns at once because the rows are selected with row locks, meaning
+          that only one scheduler can "process them", even it it is waiting behind other dags. Increasing this
+          limit will allow more throughput for smaller DAGs but will likely slow down throughput for larger
+          (>500 tasks.) DAGs
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        # Put a check in place to make sure we don't commit unexpectedly
+        with prohibit_commit(session) as guard:
+
+            if settings.USE_JOB_SCHEDULE:
+                query = DagModel.dags_needing_dagruns(session)
+                self._create_dag_runs(query.all(), session)
+
+                # commit the session - Release the write lock on DagModel table.
+                guard.commit()
+                # END: create dagruns
+
+            dag_runs = DagRun.next_dagruns_to_examine(session)
+
+            # Bulk fetch the currently active dag runs for the dags we are
+            # examining, rather than making one query per DagRun
+
+            # TODO: This query is probably horribly inefficient (though there is an
+            # index on (dag_id,state)). It is to deal with the case when a user
+            # clears more than max_active_runs older tasks -- we don't want the
+            # scheduler to suddenly go and start running tasks from all of the
+            # runs. (AIRFLOW-137/GH #1442)
+            #
+            # The longer term fix would be to have `clear` do this, and put DagRuns
+            # in to the queued state, then take DRs out of queued before creating
+            # any new ones
+            # TODO[HA]: Why is this on TI, not on DagRun??
+            currently_active_runs = dict(session.query(
+                TI.dag_id,
+                func.count(TI.execution_date.distinct()),
+            ).filter(
+                TI.dag_id.in_(list({dag_run.dag_id for dag_run in dag_runs})),
+                TI.state.notin_(State.finished())
+            ).group_by(TI.dag_id).all())
+
+            for dag_run in dag_runs:
+                self._schedule_dag_run(dag_run, currently_active_runs.get(dag_run.dag_id, 0), session)
+
+            guard.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to do it every time?
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.UP_FOR_RETRY],
+                    new_state=State.FAILED,
+                    session=session
+                )
+
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.QUEUED,
+                                State.SCHEDULED,
+                                State.UP_FOR_RESCHEDULE,
+                                State.SENSING],
+                    new_state=State.NONE,
+                    session=session
+                )
+
+                guard.commit()
+            except OperationalError as e:
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Lock held by another Scheduler")
+                    session.rollback()
+                else:
+                    raise
+
+            try:
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    session.rollback()
+                    return 0
+                raise
+
+            return num_queued_tis
+
+    def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            dag_hash = self.dagbag.dags_hash.get(dag.dag_id, None)
+            dag.create_dagrun(
+                run_type=DagRunType.SCHEDULED,
+                execution_date=dag_model.next_dagrun,
+                start_date=timezone.utcnow(),
+                state=State.RUNNING,
+                external_trigger=False,
+                session=session,
+                dag_hash=dag_hash
+            )
+
+        self._update_dag_next_dagruns(dag_models, session)
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _update_dag_next_dagruns(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Bulk update the next_dagrun and next_dagrun_create_after for all the dags.
+
+        We batch the select queries to get info about all the dags at once
+        """
+        # Check max_active_runs, to see if we are _now_ at the limit for any of
+        # these dag? (we've just created a DagRun for them after all)
+        active_runs_of_dags = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_([o.dag_id for o in dag_models]),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).group_by(DagRun.dag_id).all())
+
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            active_runs_of_dag = active_runs_of_dags.get(dag.dag_id, 0)
+            if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                    dag.dag_id, active_runs_of_dag, dag.max_active_runs
+                )
+                dag_model.next_dagrun_create_after = None
+            else:
+                dag_model.next_dagrun, dag_model.next_dagrun_create_after = \
+                    dag.next_dagrun_info(dag_model.next_dagrun)
+
+    def _schedule_dag_run(self, dag_run: DagRun, currently_active_runs: int, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        ``currently_active_runs`` is passed in so that a batch query can be
+        used to ask this for all dag runs in the batch, to avoid an n+1 query.
+
+        :param dag_run: The DagRun to schedule
+        :param currently_active_runs: Number of currently active runs of this DAG
+        :return: Number of tasks scheduled
+        """
+        dag = dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if (
+            dag_run.start_date and dag.dagrun_timeout and
+            dag_run.start_date < timezone.utcnow() - dag.dagrun_timeout
+        ):
+            dag_run.state = State.FAILED
+            dag_run.end_date = timezone.utcnow()
+            self.log.info("Run %s of %s has timed-out", dag_run.run_id, dag_run.dag_id)
+            session.flush()
+
+            # Work out if we should allow creating a new DagRun now?
+            self._update_dag_next_dagruns([session.query(DagModel).get(dag_run.dag_id)], session)
+
+            callback_to_execute = DagCallbackRequest(
+                full_filepath=dag.fileloc,
+                dag_id=dag.dag_id,
+                execution_date=dag_run.execution_date,
+                is_failure_callback=True,
+                msg='timed_out'
+            )
+
+            # Send SLA & DAG Success/Failure Callbacks to be executed
+            self._send_dag_callbacks_to_processor(dag_run, callback_to_execute)
+
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        if dag.max_active_runs:
+            if currently_active_runs >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s already has %d active runs, not queuing any more tasks",
+                    dag.dag_id,
+                    currently_active_runs,
+                )
+                return 0
+
+        self._verify_integrity_if_dag_changed(dag_run=dag_run, session=session)
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis, callback_to_run = dag_run.update_state(session=session, execute_callbacks=False)
+
+        self._send_dag_callbacks_to_processor(dag_run, callback_to_run)
+
+        # Get list of TIs that do not need to executed, these are
+        # tasks using DummyOperator and without on_execute_callback / on_success_callback
+        dummy_tis = [
+            ti for ti in schedulable_tis
+            if
+            (
+                ti.task.task_type == "DummyOperator"

Review comment:
       [Previously](https://github.com/apache/airflow/blob/eb5fea7b647e0f4b2338f86eeff6a90e1d6043bc/airflow/jobs/scheduler_job.py#L985), I used `isinstance` to handle still other operators that have no action e.g. [ExternalTaskMarker](https://github.com/apache/airflow/blob/eb5fea7b647e0f4b2338f86eeff6a90e1d6043bc/airflow/sensors/external_task_sensor.py#L225). Can you correct or add a TODO note about this limitation?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1749,62 +1403,353 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if loop_count >= self.num_runs > 0:
+                self.log.info(
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
+                )
+                break
             if self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested DAG parse count (%d) has been reached after %d "
+                    " scheduler loops",
+                    self.num_times_parse_dags, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+          Since creating Dag Runs is a relatively time consuming process, we select only 10 dags by default
+          (configurable via ``scheduler.max_dagruns_to_create_per_loop`` setting) - putting this higher will
+          mean one scheduler could spend a chunk of time creating dag runs, and not ever get around to
+          scheduling tasks.
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default, configurable
+          via ``scheduler.max_dagruns_per_loop_to_schedule`` config setting) and tries to progress state (TIs
+          to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+          The reason we don't select all dagruns at once because the rows are selected with row locks, meaning
+          that only one scheduler can "process them", even it it is waiting behind other dags. Increasing this
+          limit will allow more throughput for smaller DAGs but will likely slow down throughput for larger
+          (>500 tasks.) DAGs
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        # Put a check in place to make sure we don't commit unexpectedly
+        with prohibit_commit(session) as guard:
+
+            if settings.USE_JOB_SCHEDULE:
+                query = DagModel.dags_needing_dagruns(session)
+                self._create_dag_runs(query.all(), session)
+
+                # commit the session - Release the write lock on DagModel table.
+                guard.commit()
+                # END: create dagruns
+
+            dag_runs = DagRun.next_dagruns_to_examine(session)
+
+            # Bulk fetch the currently active dag runs for the dags we are
+            # examining, rather than making one query per DagRun
+
+            # TODO: This query is probably horribly inefficient (though there is an
+            # index on (dag_id,state)). It is to deal with the case when a user
+            # clears more than max_active_runs older tasks -- we don't want the
+            # scheduler to suddenly go and start running tasks from all of the
+            # runs. (AIRFLOW-137/GH #1442)
+            #
+            # The longer term fix would be to have `clear` do this, and put DagRuns
+            # in to the queued state, then take DRs out of queued before creating
+            # any new ones
+            # TODO[HA]: Why is this on TI, not on DagRun??
+            currently_active_runs = dict(session.query(
+                TI.dag_id,
+                func.count(TI.execution_date.distinct()),
+            ).filter(
+                TI.dag_id.in_(list({dag_run.dag_id for dag_run in dag_runs})),
+                TI.state.notin_(State.finished())
+            ).group_by(TI.dag_id).all())
+
+            for dag_run in dag_runs:
+                self._schedule_dag_run(dag_run, currently_active_runs.get(dag_run.dag_id, 0), session)
+
+            guard.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to do it every time?
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.UP_FOR_RETRY],
+                    new_state=State.FAILED,
+                    session=session
+                )
+
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.QUEUED,
+                                State.SCHEDULED,
+                                State.UP_FOR_RESCHEDULE,
+                                State.SENSING],
+                    new_state=State.NONE,
+                    session=session
+                )
+
+                guard.commit()
+            except OperationalError as e:
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Lock held by another Scheduler")
+                    session.rollback()
+                else:
+                    raise
+
+            try:
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    session.rollback()
+                    return 0
+                raise
+
+            return num_queued_tis
+
+    def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            dag_hash = self.dagbag.dags_hash.get(dag.dag_id, None)
+            dag.create_dagrun(
+                run_type=DagRunType.SCHEDULED,
+                execution_date=dag_model.next_dagrun,
+                start_date=timezone.utcnow(),
+                state=State.RUNNING,
+                external_trigger=False,
+                session=session,
+                dag_hash=dag_hash
+            )
+
+        self._update_dag_next_dagruns(dag_models, session)
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _update_dag_next_dagruns(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Bulk update the next_dagrun and next_dagrun_create_after for all the dags.
+
+        We batch the select queries to get info about all the dags at once
+        """
+        # Check max_active_runs, to see if we are _now_ at the limit for any of
+        # these dag? (we've just created a DagRun for them after all)
+        active_runs_of_dags = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_([o.dag_id for o in dag_models]),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).group_by(DagRun.dag_id).all())
+
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            active_runs_of_dag = active_runs_of_dags.get(dag.dag_id, 0)
+            if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                    dag.dag_id, active_runs_of_dag, dag.max_active_runs
+                )
+                dag_model.next_dagrun_create_after = None
+            else:
+                dag_model.next_dagrun, dag_model.next_dagrun_create_after = \
+                    dag.next_dagrun_info(dag_model.next_dagrun)
+
+    def _schedule_dag_run(self, dag_run: DagRun, currently_active_runs: int, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        ``currently_active_runs`` is passed in so that a batch query can be
+        used to ask this for all dag runs in the batch, to avoid an n+1 query.
+
+        :param dag_run: The DagRun to schedule
+        :param currently_active_runs: Number of currently active runs of this DAG
+        :return: Number of tasks scheduled
+        """
+        dag = dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if (
+            dag_run.start_date and dag.dagrun_timeout and
+            dag_run.start_date < timezone.utcnow() - dag.dagrun_timeout
+        ):
+            dag_run.state = State.FAILED
+            dag_run.end_date = timezone.utcnow()
+            self.log.info("Run %s of %s has timed-out", dag_run.run_id, dag_run.dag_id)
+            session.flush()
+
+            # Work out if we should allow creating a new DagRun now?
+            self._update_dag_next_dagruns([session.query(DagModel).get(dag_run.dag_id)], session)
+
+            callback_to_execute = DagCallbackRequest(
+                full_filepath=dag.fileloc,
+                dag_id=dag.dag_id,
+                execution_date=dag_run.execution_date,
+                is_failure_callback=True,
+                msg='timed_out'
+            )
+
+            # Send SLA & DAG Success/Failure Callbacks to be executed
+            self._send_dag_callbacks_to_processor(dag_run, callback_to_execute)
+
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        if dag.max_active_runs:
+            if currently_active_runs >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s already has %d active runs, not queuing any more tasks",
+                    dag.dag_id,
+                    currently_active_runs,
+                )
+                return 0
+
+        self._verify_integrity_if_dag_changed(dag_run=dag_run, session=session)
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis, callback_to_run = dag_run.update_state(session=session, execute_callbacks=False)
+
+        self._send_dag_callbacks_to_processor(dag_run, callback_to_run)
+
+        # Get list of TIs that do not need to executed, these are
+        # tasks using DummyOperator and without on_execute_callback / on_success_callback
+        dummy_tis = [
+            ti for ti in schedulable_tis
+            if
+            (
+                ti.task.task_type == "DummyOperator"

Review comment:
       [Previously](https://github.com/apache/airflow/blob/eb5fea7b647e0f4b2338f86eeff6a90e1d6043bc/airflow/jobs/scheduler_job.py#L985), I used `isinstance` to handle still other operators that have no action e.g. [ExternalTaskMarker](https://github.com/apache/airflow/blob/eb5fea7b647e0f4b2338f86eeff6a90e1d6043bc/airflow/sensors/external_task_sensor.py#L225). Can you fix it or add a TODO note about this limitation?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500604836



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/7fa8828b0bffb597fc681583faf8ee031bb6c76f




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] raphaelauv commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
raphaelauv commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-735451072


   @ashb thank I will 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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-700262241


   Something _odd_ is going on with the SQLite failures here. I tried to run it locally using `./breeze --github-image-id 277157900` (based on `Tagging docker.pkg.github.com/apache/airflow/master-python3.7-ci:277157900 as apache/airflow:master-python3.7-ci.` in the logs)
   
   And then running the tests locally with
   
   ```
   pytest --verbosity=0 --strict-markers --durations=100 --cov=airflow/ --cov-config=.coveragerc --cov-report=xml:/files/coverage.xml --color=yes --maxfail=50 --pythonwarnings=ignore::DeprecationWarning --pythonwarnings=ignore::PendingDeprecationWarning --junitxml=/files/test_result.xml --setup-timeout=10 --execution-timeout=30 --teardown-timeout=10 tests
   ```
   
   And they pass.
   
   I'm having trouble working out _exactly_ what is invoked in CI -- I've found ci_run_airflow_testing.sh which uses `${@}` -- but as far as I can tell that's empty?, so the args llogged above should be the same as I've run here, I think?


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r493534161



##########
File path: airflow/models/dagrun.py
##########
@@ -344,6 +393,9 @@ def update_state(self, session: Session = None) -> List[TI]:
         leaf_task_ids = {t.task_id for t in dag.leaves}
         leaf_tis = [ti for ti in tis if ti.task_id in leaf_task_ids]
 
+        # TODO[ha]: These callbacks shouldn't run in the scheduler loop - check if Kamil changed this to run

Review comment:
       Yes, this piece is ready, should hopefully be pushed today.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492342593



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Thinking more about it, a simpler rule would be easier:
   
   If a function has `@provide_session`, it must not do `session.commit()` -- only `session.flush()` is allowed.
   
   My thinking here is:
   
   - If passed an existing session, the caller is responsible for committing when they choose
   - If not passed a session, then `@provide_session` will commit for us anyway.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489381854



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -303,10 +303,10 @@ def done(self) -> bool:
         return False
 
     @property
-    def result(self) -> Optional[Tuple[List[dict], int]]:
+    def result(self) -> Optional[int]:
         """
         :return: result of running SchedulerJob.process_file()
-        :rtype: Optional[Tuple[List[dict], int]]
+        :rtype: int or None

Review comment:
       Interesting, TIL 👌 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492341310



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       I don't think this is (easily) detectable with static checks -- for instance if you call a method with the `@provide_session` decorator and forget to pass it a `session=session` param, then you will end up committing by mistake.
   
   (I was a little bit surprised by this, as I thought it should be a new or perhaps it's using a different DB connection but the events are bound to all sessions, not just one instance)
   
   It feels like a lot of work, and not 100% reliable, to write a custom pylint check when an `if not self.unit_test_mode` would have the same effect.
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499526219



##########
File path: airflow/executors/celery_executor.py
##########
@@ -225,7 +225,15 @@ def _send_tasks_to_celery(self, task_tuples_to_send):
         # since tasks are roughly uniform in size
         chunksize = self._num_tasks_per_send_process(len(task_tuples_to_send))
         num_processes = min(len(task_tuples_to_send), self._sync_parallelism)
-        with Pool(processes=num_processes) as send_pool:
+
+        def reset_signals():
+            # Since we are run from inside the SchedulerJob, we don't to
+            # inherit the signal handlers that we registered there.
+            import signal
+            signal.signal(signal.SIGINT, signal.SIG_DFL)
+            signal.signal(signal.SIGTERM, signal.SIG_DFL)
+
+        with Pool(processes=num_processes, initializer=reset_signals) as send_pool:

Review comment:
       Seems that it can have some undesired consequences if the signals are not reset. And that this is a non-HA-scheduler bug that should be fixed separately and cherry-picked to 1.10?
   
   Do I get it correctly?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499882907



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       I see this as "synchronize the state of the DB with the dags [from the dagbag]" so to me this name accurately reflect the what this method does.
   
   And because of transactions/locking, and wanting to avoid n+1 queries, the best we could do is pull out a method like below, which would still have to be called from within bulk_sync_to_db:
   
   ```python
   def _calculate_dagrun_date_fields(self, dag, most_recent_dag_run, active_runs_of_dag):
   
           self.next_dagrun, self.next_dagrun_create_after = dag.next_dagrun_info(
                  most_recent_dag_run
           )
   
           if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
               # Since this happens every time the dag is parsed it would be quite spammy at info
               log.debug(
                   "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
                   dag.dag_id, active_runs_of_dag, dag.max_active_runs
               )
               self.next_dagrun_create_after = None
   
           log.info("Setting next_dagrun for %s to %s", dag.dag_id, self.next_dagrun)
   ```
   
   Called like this:
   
   ```python
               orm_dag._calculate_dagrun_date_fields(
                   most_recent_dag_runs.get(dag.dag_id),
                   num_active_runs.get(dag.dag_id, 0)
               )
   ```
   
   Is that the sort of thing you were thinking of?
   
   (Oh except, we can't make it if it's on DagModel as we are calling from within DAG)




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492069840



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),

Review comment:
       Is it possible that `DagRun.run_id` will be None?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501627191



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       Got it, no strong opinion here but please, add a comment around this line to leave trace to why we do this




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-704563767


   I've gone and resolved all the conversations that I think have been resolved (either we've addressed them in a commit, or we said we'll tackle them in future PRs, and no one disagreed.)
   
   If you think any need re-opening please feel free to un-resolve and leave a comment saying "not done" or similar. I'm just trying to keep the "todo" list of what comments we have yet to address manageable.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-702043623


   > > This PR (with 2 Schedulers)
   > > TI Lag Avg: 74.028s (± 17.215)
   > > Time in Queued State: 68.708s (± 15.556)
   > 
   > Is the last measurement correct?
   
   Whoops yeah updated **Time in Queued State: 751.241s (± 35.5153)** for 1.10.10


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil edited a comment on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
kaxil edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-736557250


   > @ashb One more question , how do we custom the number of threads ( that are in practice processes because of the GIL ) of the scheduler ?
   > 
   > there is no more max_threads in http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/latest/configurations-ref.html#scheduler
   > 
   > Thank you
   
   `max_threads` was renamed to `parsing_processes` http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/latest/configurations-ref.html#parsing-processes


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499554188



##########
File path: airflow/models/pool.py
##########
@@ -91,7 +96,15 @@ def slots_stats(session: Session = None) -> Dict[str, PoolStats]:
 
         pools: Dict[str, PoolStats] = {}
 
-        pool_rows: Iterable[Tuple[str, int]] = session.query(Pool.pool, Pool.slots).all()
+        query = session.query(Pool.pool, Pool.slots)

Review comment:
       Those parameter names and the way the if's here are done are pretty confusing. "with_for_update" can be . Could we make the code a bit more readable and make it clear why we need for update in one place, but we do not need it in another? I think this all can be achieved by a single bool ("use_for_update") parameter ?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499536556



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:

Review comment:
       I find this a bit harder to work out what it's actually doing/checking.
   
   No strong feelings if other people agree on this though.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-705012331


   > > The "The job has been cancelled by another workflow." message is slightly confusing -- I'll look at updating that. In this case it's cancelled this PR, because the Build Image workflow failed.
   > > (The reason is there if you can connect the dots, but it's not clear on first glance)
   > 
   > @ashb The problem is that this message comes from the cancelling action which is generic, so I'd have to add an optional "cancel message". Which I will do shortly.
   
   Yeah, I figured. Was going to look at adding a new param to the cancel action to let us customize the message from our workflow yaml -- but if you are on that :+1:. I've not started yet


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494807294



##########
File path: airflow/models/dagrun.py
##########
@@ -75,6 +80,8 @@ class DagRun(Base, LoggingMixin):
         backref=backref('dag_run', uselist=False),
     )
 
+    DEFAULT_DAGRUNS_TO_EXAMINE = airflow_conf.getint('scheduler', 'max_dagruns_per_query', fallback=20)

Review comment:
       numbers picked entirely arbitrarily and it seemed to permit will in tests.
   
   The other number is hard coded still because I haven't addressed the to-do comment I already left to pull it out




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703744389


   The CI and PROD Docker Images for the build are prepared in a separate "Build Image" workflow,
   that you will not see in the list of checks (you will see "Wait for images" jobs instead).
   
   You can checks the status of those images in [The workflow run](https://github.com/apache/airflow/actions/runs/289727700)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500963489



##########
File path: airflow/models/dagrun.py
##########
@@ -94,8 +103,14 @@ def __init__(
         self.conf = conf or {}
         self.state = state
         self.run_type = run_type
+        self.dag_hash = dag_hash
+        self.callback: Optional[callback_requests.DagCallbackRequest] = None

Review comment:
       removed `dagrun.callback` in https://github.com/apache/airflow/pull/10956/commits/d8d115469c1d4436a7a1e9463df5c4c5fda2e26d
   
   Will defer the name changing of update_state to a later PR since we haven't changed any behavior i.e callbacks were executed previously. We just added a flag which will not execute the callbacks there.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706245917


   Still fewer comments than https://github.com/apache/airflow/pull/4938 :smile: 


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703754865


   You need to restart the workflow or commit --amend and push --force.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489342193



##########
File path: airflow/models/dag.py
##########
@@ -458,6 +458,99 @@ def previous_schedule(self, dttm):
         elif self.normalized_schedule_interval is not None:
             return timezone.convert_to_utc(dttm - self.normalized_schedule_interval)
 
+    def next_dagrun_info(self, date_last_automated_dagrun : Optional[pendulum.DateTime]):
+        """
+        Get information about the next DagRun of this dag after ``date_last_automated_dagrun`` -- the
+        execution date, and the earliest it could be scheduled
+
+        :param date_last_automated_dagrun: The max(execution_date) of existing
+            "automated" DagRuns for this dag (scheduled or backfill, but not
+            manual)
+        """
+        next_execution_date = self.next_dagrun_after_date(date_last_automated_dagrun)
+
+        if next_execution_date is None or self.schedule_interval in (None, '@once'):
+            return None
+
+        return {
+            'execution_date': next_execution_date,
+            'can_be_created_after': self.following_schedule(next_execution_date)
+        }
+
+    def next_dagrun_after_date(self, date_last_automated_dagrun: Optional[pendulum.DateTime]):
+        """
+        Get the next execution date after the given ``date_last_automated_dagrun``, acording to
+        schedule_interval, start_date, end_date etc.  This doesn't check max active run or any other
+        "concurrency" type limits, it only perofmrs calculations based on the varios date and interval fields
+        of this dag and it's tasks.
+
+        :param date_last_automated_dagrun: The execution_date of the last scheduler or
+            backfill triggered run for this dag
+        :type date_last_automated_dagrun: pendulum.Pendulum
+        """
+        if not self.schedule_interval:
+            return None
+
+        # don't schedule @once again
+        if self.schedule_interval == '@once' and date_last_automated_dagrun:
+            return None
+
+        # don't do scheduler catchup for dag's that don't have dag.catchup = True
+        if not (self.catchup or self.schedule_interval == '@once'):
+            # The logic is that we move start_date up until
+            # one period before, so that timezone.utcnow() is AFTER
+            # the period end, and the job can be created...
+            now = timezone.utcnow()
+            next_start = self.following_schedule(now)
+            last_start = self.previous_schedule(now)
+            if next_start <= now or isinstance(self.schedule_interval, timedelta):
+                new_start = last_start
+            else:
+                new_start = self.previous_schedule(last_start)
+
+            if self.start_date:
+                if new_start >= self.start_date:
+                    self.start_date = new_start
+            else:
+                self.start_date = new_start
+
+        next_run_date = None
+        if not date_last_automated_dagrun:
+            # First run
+            task_start_dates = [t.start_date for t in self.tasks]
+            if task_start_dates:
+                next_run_date = self.normalize_schedule(min(task_start_dates))
+                self.log.debug("Next run date based on tasks %s", next_run_date)
+        else:
+            next_run_date = self.following_schedule(date_last_automated_dagrun)
+
+        if date_last_automated_dagrun and next_run_date:
+            while next_run_date <= date_last_automated_dagrun:
+                next_run_date = self.following_schedule(next_run_date)
+
+        # don't ever schedule prior to the dag's start_date
+        if self.start_date:
+            next_run_date = self.start_date if not next_run_date else max(next_run_date, self.start_date)
+            if next_run_date == self.start_date:
+                next_run_date = self.normalize_schedule(self.start_date)
+
+            self.log.debug(
+                "Dag start date: %s. Next run date: %s",
+                self.start_date, next_run_date
+            )
+
+        # Don't schedule a dag beyond its end_date (as specified by the dag param)
+        if next_run_date and self.end_date and next_run_date > self.end_date:
+            return None
+
+        # Don't schedule a dag beyond its end_date (as specified by the task params)
+        # Get the min task end date, which may come from the dag.default_args
+        task_end_dates = [t.end_date for t in self.tasks if t.end_date]
+        if task_end_dates and next_run_date:
+            min_task_end_date = min(task_end_dates)
+            if next_run_date > min_task_end_date:
+                return None
+

Review comment:
       When does this method return a result?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499588584



##########
File path: airflow/models/pool.py
##########
@@ -91,7 +96,15 @@ def slots_stats(session: Session = None) -> Dict[str, PoolStats]:
 
         pools: Dict[str, PoolStats] = {}
 
-        pool_rows: Iterable[Tuple[str, int]] = session.query(Pool.pool, Pool.slots).all()
+        query = session.query(Pool.pool, Pool.slots)

Review comment:
       Yeah, this went through a few iterations, and I agree it should be tided up now.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501239858



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       Is this somehow configurable or we are just hardcoding it?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r488900780



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -303,10 +303,10 @@ def done(self) -> bool:
         return False
 
     @property
-    def result(self) -> Optional[Tuple[List[dict], int]]:
+    def result(self) -> Optional[int]:
         """
         :return: result of running SchedulerJob.process_file()
-        :rtype: Optional[Tuple[List[dict], int]]
+        :rtype: int or None

Review comment:
       ```suggestion
           :rtype: Optional[None]
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501529477



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       It's not used in every test is the issue, so we don't want to always set it when unittest is enabled.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       Will do

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       Added in d09c846d9 

##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       Done in 63ae0f5c4 - I settled on `bulk_write_to_db` (update could be taken to be UPDATE, but we will INSERT too)

##########
File path: tests/jobs/test_backfill_job.py
##########
@@ -160,10 +160,11 @@ def test_trigger_controller_dag(self):
         )
         job.run()
 
-        task_instances_list = dag_file_processor._process_task_instances(
-            target_dag,
-            dag_runs=DagRun.find(dag_id='example_trigger_target_dag')
-        )
+        task_instances_list = []

Review comment:
       Yes, working on this now.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499826539



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1714,53 +1321,158 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to

Review comment:
       (here is the right place to mention the config, certainly.)




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491876853



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)

Review comment:
       Yup

##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       It is, yes, but I can do this better
   
   In [dagrun.py](https://github.com/apache/airflow/pull/10956/files#diff-32aa8dbb910719ef24a39cab5d0f2a97L376-L379) I removed the commit (on purpose) but also removed the merge by mistake:
   
   ```diff
   -        # todo: determine we want to use with_for_update to make sure to lock the run
   -        session.merge(self)
   -        session.commit()
   -
   ```
   
   ->
   
   
   ```diff
   -        # todo: determine we want to use with_for_update to make sure to lock the run
           session.merge(self)
   -        session.commit()
   -
   ```

##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       See https://github.com/apache/airflow/pull/10956#discussion_r492048058 (can remove this entirely.)

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       Do you mean have a DbDagBag and a FileDagBag class, or something of that nature?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       It didn't seem to cause any problems on 5.7 when running with just a single scheduler -- we ran some of our medium sized benchmarks and it behaved as before.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Sure, will create a txn manager.
   
   I think keeping it for unit/integration tests is the right thing to do, I'm open to discussion if we should remove it for "runtime".

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),

Review comment:
       Exceeding unlikely (Maybe if you deleted the dag_run via the Browse -> DagRuns, I think that used to be possible but isn't anymore), but the existing code allowed it, and we have unit tests that check for it, so to keep this change smaller I didn't remove it.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       > * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you're adventurous, but expect moderate gains and higher risks of concurrency related problems
   > 
   > * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems.
   
   Yes, this matches with our testing so far.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       I don't think this is (easily) detectable with static checks -- for instance if you call a method with the `@provide_session` decorator and forget to pass it a `session=session` param, then you will end up committing by mistake.
   
   (I was a little bit surprised by this, as I thought it should be a new or perhaps it's using a different DB connection but the events are bound to all sessions, not just one instance)
   
   It feels like a lot of work, and not 100% reliable, to write a custom pylint check when an `if not self.unit_test_mode` would have the same effect.
   

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Thinking more about it, a simpler rule would be easier:
   
   If a function has `@provide_session`, it must not do `session.commit()` -- only `session.flush()` is allowed.
   
   My thinking here is:
   
   - If passed an existing session, the caller is responsible for committing when they choose
   - If not passed a session, then `@provide_session` will commit for us anyway.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499516102



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       It is related to the https://github.com/apache/airflow/pull/10956#discussion_r499491362




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-700535970


   Ah, I didn't realise it stored the last used DB, neat


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494808195



##########
File path: airflow/models/dag.py
##########
@@ -1941,6 +2087,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        return session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(10).with_for_update(of=cls, **skip_locked(session=session))

Review comment:
       ```python
   		        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
   		        # doesn't try to do all the creation of dag runs
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489376805



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1707,53 +1343,119 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
-            try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
-        )
-        self._execute_task_instances(simple_dag_bag)
+    def _scheduler_loop_critical_section(self, dag_bag, session) -> Union[int, _NoLockObtained]:
+        """

Review comment:
       Fixed in 783b91162




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502479216



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -868,122 +608,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
             self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Error executing failure callback!")
 
-        # Save individual DAGs in the ORM and update DagModel.last_scheduled_time
+        # Save individual DAGs in the ORM
+        dagbag.read_dags_from_db = True

Review comment:
       @turbaszek can you say something more?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-702037209


    > This PR (with 2 Schedulers)
   TI Lag Avg: 74.028s (± 17.215)
   Time in Queued State: 68.708s (± 15.556)
   
   Is the last measurement correct?


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706260599


   > LGTM. I have one little request. Could you please some documentation in the follow-up PR? It is very important for me to note that MySQL 8.0 is required to be able to use HA. I still have a lot of users who are using older versions of MySQL, so I need some documentation that details the limitations to convince them to migrate to the newer version.
   
   Yes, absolutely. That's my next week's task for certain.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499643749



##########
File path: airflow/utils/sqlalchemy.py
##########
@@ -141,3 +142,107 @@ def skip_locked(session: Session) -> Dict[str, Any]:
         return {'skip_locked': True}
     else:
         return {}
+
+
+def nowait(session: Session) -> Dict[str, Any]:
+    """
+    Return kwargs for passing to `with_for_update()` suitable for the current DB engine version.
+
+    We do this as we document the fact that on DB engines that don't support this construct, we do not
+    support/recommend running HA scheduler. If a user ignores this and tries anyway everything will still
+    work, just slightly slower in some circumstances.
+
+    Specifically don't emit NOWAIT for MySQL < 8, or MariaDB, neither of which support this construct
+
+    See https://jira.mariadb.org/browse/MDEV-13115
+    """
+    dialect = session.bind.dialect
+
+    if dialect.name != "mysql" or dialect.supports_for_update_of:
+        return {'nowait': True}
+    else:
+        return {}
+
+
+def nulls_first(col, session: Session) -> Dict[str, Any]:
+    """
+    Adds a nullsfirst construct to the column ordering. Currently only Postgres supports it.
+    In MySQL & Sqlite NULL values are considered lower than any non-NULL value, therefore, NULL values
+    appear first when the order is ASC (ascending)
+    """
+    if session.bind.dialect.name == "postgresql":
+        return nullsfirst(col)
+    else:
+        return col
+
+
+USE_ROW_LEVEL_LOCKING: bool = conf.getboolean('scheduler', 'use_row_level_locking', fallback=True)
+
+
+def with_for_update(query, **kwargs):

Review comment:
       Perfect!




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb merged pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb merged pull request #10956:
URL: https://github.com/apache/airflow/pull/10956


   


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706423948


   :tada: 


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499536556



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:

Review comment:
       I find this a bit harder to work out what it's actually doing/checking.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r493511009



##########
File path: airflow/models/dagrun.py
##########
@@ -494,12 +542,13 @@ def verify_integrity(self, session: Session = None):
                 session.add(ti)
 
         try:
-            session.commit()
+            session.flush()

Review comment:
       What's the reason for the integrity error here? Is the Integrity error here still valid if we do not commit to the database? I think flush is not likely to generate Integrity Error at all.
   
   Shoudl we start caring about isolation level of the transactions we have ? Will it work when we have different isolation levels set ?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492164281



##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       See https://github.com/apache/airflow/pull/10956#discussion_r492048058 (can remove this entirely.)




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-702041010


   > > This PR (with 2 Schedulers)
   > > TI Lag Avg: 74.028s (± 17.215)
   > > Time in Queued State: 68.708s (± 15.556)
   > 
   > Is the last measurement correct?
   
   Yeah. Looks like copy&paste error ? 


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706331789


   We're trying to get this PR green before merging, because although it doesn't _matter_ we know it's possible and it feels like an important one to say "yes, this is all good"


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499548876



##########
File path: airflow/models/dagrun.py
##########
@@ -94,8 +103,14 @@ def __init__(
         self.conf = conf or {}
         self.state = state
         self.run_type = run_type
+        self.dag_hash = dag_hash
+        self.callback: Optional[callback_requests.DagCallbackRequest] = None

Review comment:
       So have `ready_tis, callbacks_to_run = dagrun.update_state()`? 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492217257



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       > * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you're adventurous, but expect moderate gains and higher risks of concurrency related problems
   > 
   > * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems.
   
   Yes, this matches with our testing so far.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-705006631


   For me there are just two points left to be done in this or -> the bulk_sync_db and a question about task_instance [] left.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502475807



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -303,10 +303,10 @@ def done(self) -> bool:
         return False
 
     @property
-    def result(self) -> Optional[Tuple[List[dict], int]]:
+    def result(self) -> Optional[int]:
         """
         :return: result of running SchedulerJob.process_file()
-        :rtype: Optional[Tuple[List[dict], int]]
+        :rtype: int or None

Review comment:
       This function returns tuple or None. The description in the pydocstring is incorrect.
   `int or None` != `Optional[Tuple[int, int]]`




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492052170



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -868,122 +608,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
             self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Error executing failure callback!")
 
-        # Save individual DAGs in the ORM and update DagModel.last_scheduled_time
+        # Save individual DAGs in the ORM
+        dagbag.read_dags_from_db = True

Review comment:
       Why we don't initialize the `DagBag` in L607 with this parameter?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499552049



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       A separate class doesn't feel right to me -- calculating the values for these fields is very much a property of the dag, and keeping all the logic in one class feels easier to follow than having some part of the dag model updated in a separate class.
   
   This is also why I put the new code in here -- the job of this method is to ensure that the DagModel row in the database is in sync. Since the two new data columns are on the row, I updated them all in one place. 
   
   Particularly because of the `with_for_update` used here (and already in use in master -- not added by my PR) we'd a have to update those columns in the same transaction.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500595543



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -867,122 +631,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
-            self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
+            self.execute_callbacks(dagbag, callback_requests)

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/b4764f0b563ad61004bcd73e30b02b160650244c




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499578249



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:
+                self.log.info(
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
+                )
+                break
             if self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested DAG parse count (%d) has been reached after %d "
+                    " scheduler loops",
+                    self.num_times_parse_dags, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        # Put a check in place to make sure we don't commit unexpectedly
+        with prohibit_commit(session) as guard:
+
+            query = DagModel.dags_needing_dagruns(session)
+            self._create_dag_runs(query.all(), session)
+
+            # commit the session - Release the write lock on DagModel table.
+            guard.commit()
+            # END: create dagruns
+
+            dag_runs = DagRun.next_dagruns_to_examine(session)
+
+            # Bulk fetch the currently active dag runs for the dags we are
+            # examining, rather than making one query per DagRun
+
+            # TODO: This query is probably horribly inefficient (though there is an
+            # index on (dag_id,state)). It is to deal with the case when a user
+            # clears more than max_active_runs older tasks -- we don't want the
+            # scheduler to suddenly go and start running tasks from all of the
+            # runs. (AIRFLOW-137/GH #1442)
+            #
+            # The longer term fix would be to have `clear` do this, and put DagRuns
+            # in to the queued state, then take DRs out of queued before creating
+            # any new ones
+            # TODO[HA]: Why is this on TI, not on DagRun??
+            currently_active_runs = dict(session.query(
+                TI.dag_id,
+                func.count(TI.execution_date.distinct()),
+            ).filter(
+                TI.dag_id.in_(list({dag_run.dag_id for dag_run in dag_runs})),
+                TI.state.notin_(State.finished())
+            ).group_by(TI.dag_id).all())
+
+            for dag_run in dag_runs:
+                self._schedule_dag_run(dag_run, currently_active_runs.get(dag_run.dag_id, 0), session)
+
+            guard.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    session.rollback()
+                    return 0
+                raise
+
+            return num_queued_tis
+
+    def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            dag_hash = self.dagbag.dags_hash.get(dag.dag_id, None)
+            dag.create_dagrun(
+                run_type=DagRunType.SCHEDULED,
+                execution_date=dag_model.next_dagrun,
+                start_date=timezone.utcnow(),
+                state=State.RUNNING,
+                external_trigger=False,
+                session=session,
+                dag_hash=dag_hash
+            )
+
+        self._update_dag_next_dagruns(dag_models, session)
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _update_dag_next_dagruns(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Bulk update the next_dagrun and next_dagrun_create_after for all the dags.
+
+        We batch the select queries to get info about all the dags at once
+        """
+        # Check max_active_runs, to see if we are _now_ at the limit for any of
+        # these dag? (we've just created a DagRun for them after all)
+        active_runs_of_dags = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_([o.dag_id for o in dag_models]),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).group_by(DagRun.dag_id).all())
+
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            active_runs_of_dag = active_runs_of_dags.get(dag.dag_id, 0)
+            if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                    dag.dag_id, active_runs_of_dag, dag.max_active_runs
+                )
+                dag_model.next_dagrun_create_after = None
+            else:
+                dag_model.next_dagrun, dag_model.next_dagrun_create_after = \
+                    dag.next_dagrun_info(dag_model.next_dagrun)
+
+    def _schedule_dag_run(self, dag_run: DagRun, currently_active_runs: int, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        ``currently_active_runs`` is passed in so that a batch query can be
+        used to ask this for all dag runs in the batch, to avoid an n+1 query.
+
+        :param dag_run: The DagRun to schedule
+        :param currently_active_runs: Number of currently active runs of this DAG
+        :return: Number of tasks scheduled
+        """
+        dag = dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if (
+            dag_run.start_date and dag.dagrun_timeout and
+            dag_run.start_date < timezone.utcnow() - dag.dagrun_timeout
+        ):
+            dag_run.state = State.FAILED
+            dag_run.end_date = timezone.utcnow()
+            self.log.info("Run %s of %s has timed-out", dag_run.run_id, dag_run.dag_id)
+            session.flush()
+
+            # Work out if we should allow creating a new DagRun now?
+            self._update_dag_next_dagruns([session.query(DagModel).get(dag_run.dag_id)], session)
+
+            dag_run.callback = DagCallbackRequest(
+                full_filepath=dag.fileloc,
+                dag_id=dag.dag_id,
+                execution_date=dag_run.execution_date,
+                is_failure_callback=True,
+                msg='timed_out'
+            )
+
+            # Send SLA & DAG Success/Failure Callbacks to be executed
+            self._send_dag_callbacks_to_processor(dag_run)
+
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        if dag.max_active_runs:
+            if currently_active_runs >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s already has %d active runs, not queuing any more tasks",
+                    dag.dag_id,
+                    currently_active_runs,
+                )
+                return 0
+
+        self._verify_integrity_if_dag_changed(dag_run=dag_run, session=session)
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session, execute_callbacks=False)
+        # TODO[HA]: Don't return, update these from in update_state?
+
+        # Get list of TIs that do not need to executed, these are
+        # tasks using DummyOperator and without on_execute_callback / on_success_callback
+        dummy_tis = [
+            ti for ti in schedulable_tis
+            if
+            (
+                ti.task.task_type == "DummyOperator"
+                and not ti.task.on_execute_callback
+                and not ti.task.on_success_callback
+            )
+        ]
+
+        # This will do one query per dag run. We "could" build up a complex
+        # query to update all the TIs across all the execution dates and dag
+        # IDs in a single query, but it turns out that can be _very very slow_
+        # see #11147/commit ee90807ac for more details
+        count = session.query(TI).filter(
+            TI.dag_id == dag_run.dag_id,
+            TI.execution_date == dag_run.execution_date,
+            TI.task_id.in_(ti.task_id for ti in schedulable_tis if ti not in dummy_tis)
+        ).update({TI.state: State.SCHEDULED}, synchronize_session=False)
+
+        # Tasks using DummyOperator should not be executed, mark them as success
+        if dummy_tis:
+            session.query(TI).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.execution_date == dag_run.execution_date,
+                TI.task_id.in_(ti.task_id for ti in dummy_tis)
+            ).update({
+                TI.state: State.SUCCESS,
+                TI.start_date: timezone.utcnow(),
+                TI.end_date: timezone.utcnow(),
+                TI.duration: 0
+            }, synchronize_session=False)
+
+        return count
+
+    @provide_session
+    def _verify_integrity_if_dag_changed(self, dag_run: DagRun, session=None):
+        """Only run DagRun.verify integrity if Serialized DAG has changed since it is slow"""
+        latest_version = SerializedDagModel.get_latest_version_hash(dag_run.dag_id, session=session)
+        if dag_run.dag_hash == latest_version:
+            self.log.debug("DAG %s not changed structure, skipping dagrun.verify_integrity", dag_run.dag_id)
+            return
+
+        dag_run.dag_hash = latest_version
+
+        # Refresh the DAG
+        dag_run.dag = self.dagbag.get_dag(dag_id=dag_run.dag_id, session=session)
+
+        # Verify integrity also takes care of session.flush
+        dag_run.verify_integrity(session=session)
+
+    def _send_dag_callbacks_to_processor(self, dag_run: DagRun):
+        if not self.processor_agent:
+            raise ValueError("Processor agent is not started.")
+
+        dag = dag_run.get_dag()
+        self._manage_slas(dag)
+        if dag_run.callback:
+            self.processor_agent.send_callback_to_execute(dag_run.callback)
+
+    def _manage_slas(self, dag: DAG):

Review comment:
       Can change it to `_send_sla_callbacks`, WDYT?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499578109



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:

Review comment:
       I'm afraid that pylint will require this anyway - we are still not running it over those files:
   ```
   R1716: Simplify chained comparison between the operands (chained-comparison)
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499510807



##########
File path: airflow/models/dag.py
##########
@@ -1939,6 +2099,37 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        query = session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(cls.NUM_DAGS_PER_DAGRUN_QUERY)
+
+        return with_for_update(query, of=cls, **skip_locked(session=session))
+
+
+STATICA_HACK = True

Review comment:
       This is a nasty hack and it should rather be solved by splitting the classes differently. This seems like architectural problem that might be likely solved by restructuring the class hierarchy




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500606634



##########
File path: airflow/models/dag.py
##########
@@ -1824,10 +1960,34 @@ class DagModel(Base):
     # Tags for view filter
     tags = relationship('DagTag', cascade='all,delete-orphan', backref=backref('dag'))
 
+    concurrency = Column(Integer, nullable=False)
+
+    has_task_concurrency_limits = Column(Boolean, nullable=False)
+
+    # The execution_date of the next dag run
+    next_dagrun = Column(UtcDateTime)
+    # Earliest time at which this ``next_dagrun`` can be created
+    next_dagrun_create_after = Column(UtcDateTime)
+
     __table_args__ = (
         Index('idx_root_dag_id', root_dag_id, unique=False),
+        Index('idx_next_dagrun_create_after', next_dagrun_create_after, unique=False),
     )
 
+    NUM_DAGS_PER_DAGRUN_QUERY = conf.getint(
+        'scheduler',
+        'num_dags_needing_dagrun_per_scheduler_loop',
+        fallback=10
+    )

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/51d1d0e96d9b279cf7f32de14bda7a9d4ae9aea5




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] dimberman commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
dimberman commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491140287



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1464,23 +1070,21 @@ def _execute_task_instances(
         2. Change the state for the TIs above atomically.
         3. Enqueue the TIs in the executor.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        HA note: This function is a "critical section" meaning that only a single executor process can execute
+        this function at the same time. This is achived by doing ``SELECT ... from pool FOR UPDATE``. For DBs

Review comment:
       ```suggestion
           this function at the same time. This is achieved by doing ``SELECT ... from pool FOR UPDATE``. For DBs
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499841037



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1714,53 +1321,158 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to

Review comment:
       I would be in favor of adding this to config and then documenting it.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491342764



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       And, to be clear, if the performance isn't good enough I'll change something beck to make in non-blocking in some way




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492065450



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))

Review comment:
       ```suggestion
           pool_slots_free = max(0, sum(v["open"] for v in pools.values()))
   ```
   How about simplifying it?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501091277



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       Agree with @kaxil - > separating it out and adding docstring should do the job




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r498462551



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/ef9101ff910eba85a2782f894f0e9dfbafc04689 -- I think keeping it at runtime is the easiest for now -- it doesn't add much overhead.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501236528



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -567,302 +567,71 @@ def update_import_errors(session: Session, dagbag: DagBag) -> None:
                 stacktrace=stacktrace))
         session.commit()
 
-    # pylint: disable=too-many-return-statements,too-many-branches
     @provide_session
-    def create_dag_run(
-        self,
-        dag: DAG,
-        dag_runs: Optional[List[DagRun]] = None,
-        session: Session = None,
-    ) -> Optional[DagRun]:
-        """
-        This method checks whether a new DagRun needs to be created
-        for a DAG based on scheduling interval.
-        Returns DagRun if one is scheduled. Otherwise returns None.
-        """
-        # pylint: disable=too-many-nested-blocks
-        if not dag.schedule_interval:
-            return None
-
-        active_runs: List[DagRun]
-        if dag_runs is None:
-            active_runs = DagRun.find(
-                dag_id=dag.dag_id,
-                state=State.RUNNING,
-                external_trigger=False,
-                session=session
-            )
-        else:
-            active_runs = [
-                dag_run
-                for dag_run in dag_runs
-                if not dag_run.external_trigger
-            ]
-        # return if already reached maximum active runs and no timeout setting
-        if len(active_runs) >= dag.max_active_runs and not dag.dagrun_timeout:
-            return None
-        timed_out_runs = 0
-        for dr in active_runs:
-            if (
-                dr.start_date and dag.dagrun_timeout and
-                dr.start_date < timezone.utcnow() - dag.dagrun_timeout
-            ):
-                dr.state = State.FAILED
-                dr.end_date = timezone.utcnow()
-                dag.handle_callback(dr, success=False, reason='dagrun_timeout',
-                                    session=session)
-                timed_out_runs += 1
-        session.commit()
-        if len(active_runs) - timed_out_runs >= dag.max_active_runs:
-            return None
-
-        # this query should be replaced by find dagrun
-        last_scheduled_run: Optional[datetime.datetime] = (
-            session.query(func.max(DagRun.execution_date))
-            .filter_by(dag_id=dag.dag_id)
-            .filter(or_(
-                DagRun.external_trigger == False,  # noqa: E712 pylint: disable=singleton-comparison
-                DagRun.run_type == DagRunType.SCHEDULED.value
-            )).scalar()
-        )
-
-        # don't schedule @once again
-        if dag.schedule_interval == '@once' and last_scheduled_run:
-            return None
-
-        # don't do scheduler catchup for dag's that don't have dag.catchup = True
-        if not (dag.catchup or dag.schedule_interval == '@once'):
-            # The logic is that we move start_date up until
-            # one period before, so that timezone.utcnow() is AFTER
-            # the period end, and the job can be created...
-            now = timezone.utcnow()
-            next_start = dag.following_schedule(now)
-            last_start = dag.previous_schedule(now)
-            if next_start <= now or isinstance(dag.schedule_interval, timedelta):
-                new_start = last_start
-            else:
-                new_start = dag.previous_schedule(last_start)
-
-            if dag.start_date:
-                if new_start >= dag.start_date:
-                    dag.start_date = new_start
-            else:
-                dag.start_date = new_start
-
-        next_run_date = None
-        if not last_scheduled_run:
-            # First run
-            task_start_dates = [t.start_date for t in dag.tasks]
-            if task_start_dates:
-                next_run_date = dag.normalize_schedule(min(task_start_dates))
-                self.log.debug(
-                    "Next run date based on tasks %s",
-                    next_run_date
-                )
-        else:
-            next_run_date = dag.following_schedule(last_scheduled_run)
-
-        # make sure backfills are also considered
-        last_run = dag.get_last_dagrun(session=session)
-        if last_run and next_run_date:
-            while next_run_date <= last_run.execution_date:
-                next_run_date = dag.following_schedule(next_run_date)
-
-        # don't ever schedule prior to the dag's start_date
-        if dag.start_date:
-            next_run_date = (dag.start_date if not next_run_date
-                             else max(next_run_date, dag.start_date))
-            if next_run_date == dag.start_date:
-                next_run_date = dag.normalize_schedule(dag.start_date)
-
-            self.log.debug(
-                "Dag start date: %s. Next run date: %s",
-                dag.start_date, next_run_date
-            )
-
-        # don't ever schedule in the future or if next_run_date is None
-        if not next_run_date or next_run_date > timezone.utcnow():
-            return None
-
-        # this structure is necessary to avoid a TypeError from concatenating
-        # NoneType
-        period_end = None
-        if dag.schedule_interval == '@once':
-            period_end = next_run_date
-        elif next_run_date:
-            period_end = dag.following_schedule(next_run_date)
-
-        # Don't schedule a dag beyond its end_date (as specified by the dag param)
-        if next_run_date and dag.end_date and next_run_date > dag.end_date:
-            return None
-
-        # Don't schedule a dag beyond its end_date (as specified by the task params)
-        # Get the min task end date, which may come from the dag.default_args
-        min_task_end_date = min([t.end_date for t in dag.tasks if t.end_date], default=None)
-        if next_run_date and min_task_end_date and next_run_date > min_task_end_date:
-            return None
-
-        if next_run_date and period_end and period_end <= timezone.utcnow():
-            next_run = dag.create_dagrun(
-                run_type=DagRunType.SCHEDULED,
-                execution_date=next_run_date,
-                start_date=timezone.utcnow(),
-                state=State.RUNNING,
-                external_trigger=False
-            )
-            return next_run
-
-        return None
-
-    @provide_session
-    def _process_task_instances(
-        self, dag: DAG, dag_runs: List[DagRun], session: Session = None
-    ) -> List[TaskInstanceKey]:
-        """
-        This method schedules the tasks for a single DAG by looking at the
-        active DAG runs and adding task instances that should run to the
-        queue.
-        """
-        # update the state of the previously active dag runs
-        active_dag_runs = 0
-        task_instances_list = []
-        for run in dag_runs:
-            self.log.info("Examining DAG run %s", run)
-            # don't consider runs that are executed in the future unless
-            # specified by config and schedule_interval is None
-            if run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
-                self.log.error(
-                    "Execution date is in future: %s",
-                    run.execution_date
-                )
-                continue
-
-            if active_dag_runs >= dag.max_active_runs:
-                self.log.info("Number of active dag runs reached max_active_run.")
-                break
-
-            # skip backfill dagruns for now as long as they are not really scheduled
-            if run.is_backfill:
-                continue
-
-            # todo: run.dag is transient but needs to be set
-            run.dag = dag  # type: ignore
-            # todo: preferably the integrity check happens at dag collection time
-            run.verify_integrity(session=session)
-            ready_tis = run.update_state(session=session)
-            if run.state == State.RUNNING:
-                active_dag_runs += 1
-                self.log.debug("Examining active DAG run: %s", run)
-                for ti in ready_tis:
-                    self.log.debug('Queuing task: %s', ti)
-                    task_instances_list.append(ti.key)
-        return task_instances_list
-
-    @provide_session
-    def _process_dags(self, dags: List[DAG], session: Session = None) -> List[TaskInstanceKey]:
-        """
-        Iterates over the dags and processes them. Processing includes:
-
-        1. Create appropriate DagRun(s) in the DB.
-        2. Create appropriate TaskInstance(s) in the DB.
-        3. Send emails for tasks that have missed SLAs (if CHECK_SLAS config enabled).
-
-        :param dags: the DAGs from the DagBag to process
-        :type dags: List[airflow.models.DAG]
-        :rtype: list[TaskInstance]
-        :return: A list of generated TaskInstance objects
-        """
-        check_slas: bool = conf.getboolean('core', 'CHECK_SLAS', fallback=True)
-        use_job_schedule: bool = conf.getboolean('scheduler', 'USE_JOB_SCHEDULE')
-
-        # pylint: disable=too-many-nested-blocks
-        tis_out: List[TaskInstanceKey] = []
-        dag_ids: List[str] = [dag.dag_id for dag in dags]
-        dag_runs = DagRun.find(dag_id=dag_ids, state=State.RUNNING, session=session)
-        # As per the docs of groupby (https://docs.python.org/3/library/itertools.html#itertools.groupby)
-        # we need to use `list()` otherwise the result will be wrong/incomplete
-        dag_runs_by_dag_id: Dict[str, List[DagRun]] = {
-            k: list(v) for k, v in groupby(dag_runs, lambda d: d.dag_id)
-        }
-
-        for dag in dags:
-            dag_id: str = dag.dag_id
-            self.log.info("Processing %s", dag_id)
-            dag_runs_for_dag = dag_runs_by_dag_id.get(dag_id) or []
-
-            # Only creates DagRun for DAGs that are not subdag since
-            # DagRun of subdags are created when SubDagOperator executes.
-            if not dag.is_subdag and use_job_schedule:
-                dag_run = self.create_dag_run(dag, dag_runs=dag_runs_for_dag)
-                if dag_run:
-                    dag_runs_for_dag.append(dag_run)
-                    expected_start_date = dag.following_schedule(dag_run.execution_date)
-                    if expected_start_date:
-                        schedule_delay = dag_run.start_date - expected_start_date
-                        Stats.timing(
-                            'dagrun.schedule_delay.{dag_id}'.format(dag_id=dag.dag_id),
-                            schedule_delay)
-                    self.log.info("Created %s", dag_run)
-
-            if dag_runs_for_dag:
-                tis_out.extend(self._process_task_instances(dag, dag_runs_for_dag))
-                if check_slas:
-                    self.manage_slas(dag)
-
-        return tis_out
-
-    def _find_dags_to_process(self, dags: List[DAG]) -> List[DAG]:
-        """
-        Find the DAGs that are not paused to process.
-
-        :param dags: specified DAGs
-        :return: DAGs to process
-        """
-        if self.dag_ids:
-            dags = [dag for dag in dags
-                    if dag.dag_id in self.dag_ids]
-        return dags
-
-    @provide_session
-    def execute_on_failure_callbacks(
+    def execute_callbacks(
         self,
         dagbag: DagBag,
-        failure_callback_requests: List[FailureCallbackRequest],
+        callback_requests: List[CallbackRequest],
         session: Session = None
     ) -> None:
         """
         Execute on failure callbacks. These objects can come from SchedulerJob or from
         DagFileProcessorManager.
 
-        :param failure_callback_requests: failure callbacks to execute
-        :type failure_callback_requests: List[airflow.utils.dag_processing.FailureCallbackRequest]
+        :param dagbag: Dag Bag of dags
+        :param callback_requests: failure callbacks to execute
+        :type callback_requests: List[airflow.utils.callback_requests.CallbackRequest]
         :param session: DB session.
         """
-        for request in failure_callback_requests:
-            simple_ti = request.simple_task_instance
-            if simple_ti.dag_id in dagbag.dags:
-                dag = dagbag.dags[simple_ti.dag_id]
-                if simple_ti.task_id in dag.task_ids:
-                    task = dag.get_task(simple_ti.task_id)
-                    ti = TI(task, simple_ti.execution_date)
-                    # Get properties needed for failure handling from SimpleTaskInstance.
-                    ti.start_date = simple_ti.start_date
-                    ti.end_date = simple_ti.end_date
-                    ti.try_number = simple_ti.try_number
-                    ti.state = simple_ti.state
-                    ti.test_mode = self.UNIT_TEST_MODE
+        for request in callback_requests:
+            try:
+                if isinstance(request, TaskCallbackRequest):
+                    self._execute_task_callbacks(dagbag, request)
+                elif isinstance(request, SlaCallbackRequest):
+                    self.manage_slas(dagbag.dags.get(request.dag_id))
+                elif isinstance(request, DagCallbackRequest):
+                    self._execute_dag_callbacks(dagbag, request, session)
+            except Exception:  # pylint: disable=broad-except
+                self.log.exception("Error executing callback for File: %s", request.full_filepath)

Review comment:
       ```suggestion
                   self.log.exception("Error executing %s callback for file: %s", request.__class__.__name__, request.full_filepath)
   ```
   Just to give more information 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-692859496


   Cool. Looking at it


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499689634



##########
File path: airflow/models/dag.py
##########
@@ -1939,6 +2099,37 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        query = session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(cls.NUM_DAGS_PER_DAGRUN_QUERY)
+
+        return with_for_update(query, of=cls, **skip_locked(session=session))
+
+
+STATICA_HACK = True

Review comment:
       > I think if we agree that we should continue our refactoring after this merge I think I will be fine in deferring this work to the beta iterations.
   
   Yeah, Always Be Refactoring :grin: 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499519623



##########
File path: airflow/models/dag.py
##########
@@ -1939,6 +2099,37 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        query = session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(cls.NUM_DAGS_PER_DAGRUN_QUERY)
+
+        return with_for_update(query, of=cls, **skip_locked(session=session))
+
+
+STATICA_HACK = True

Review comment:
       This is a pattern we already use in `airflow/__init__.py`




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492048058



##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       Is this change related to scheduler HA?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -868,122 +608,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
             self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Error executing failure callback!")
 
-        # Save individual DAGs in the ORM and update DagModel.last_scheduled_time
+        # Save individual DAGs in the ORM
+        dagbag.read_dags_from_db = True

Review comment:
       Why we don't initialize the `DagBag` in L607 with this parameter?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))

Review comment:
       ```suggestion
           pool_slots_free = max(0, sum(v["open"] for v in pools.values()))
   ```
   How about simplifying it?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),

Review comment:
       Is it possible that `DagRun.run_id` will be None?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703845760


   [The Build Workflow run](https://github.com/apache/airflow/actions/runs/289987522) is cancelling this PR. The job has been cancelled by another workflow.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499624315



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:

Review comment:
       Good enough for me then




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492194999



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),

Review comment:
       Yeah. We can remove it later in separate commit.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492188003



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       I see. I still have to wrap my head around the locking consequences here. I understand that here the only locked tables will be TI and DR. the DM is "selectinload"  so likely not locked.
   
   I really just want to understand the consequences and risks. I think a the end we should come up with some "cautious" recommendations to the users. After looking at the potential issues and gains, my current feeling (but needs a bit deeper thinking and testing) is that 
   
   * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you'r adventurous, but expect moderate gains and higher risks of concurrently related problems
   * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems. 
   
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499840548



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -556,12 +556,15 @@ def execute_callbacks(
         :param session: DB session.
         """
         for request in callback_requests:
-            if isinstance(request, TaskCallbackRequest):
-                self._execute_task_callbacks(dagbag, request)
-            elif isinstance(request, SlaCallbackRequest):
-                self.manage_slas(dagbag.dags.get(request.dag_id))
-            elif isinstance(request, DagCallbackRequest):
-                self._execute_dag_callbacks(dagbag, request, session)
+            try:
+                if isinstance(request, TaskCallbackRequest):
+                    self._execute_task_callbacks(dagbag, request)
+                elif isinstance(request, SlaCallbackRequest):
+                    self.manage_slas(dagbag.dags.get(request.dag_id))

Review comment:
       Just a nit, but as we are refactoring code here should we make `manage_slas` private too?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499554188



##########
File path: airflow/models/pool.py
##########
@@ -91,7 +96,15 @@ def slots_stats(session: Session = None) -> Dict[str, PoolStats]:
 
         pools: Dict[str, PoolStats] = {}
 
-        pool_rows: Iterable[Tuple[str, int]] = session.query(Pool.pool, Pool.slots).all()
+        query = session.query(Pool.pool, Pool.slots)

Review comment:
       Those parameter names and the way the if's here are done are pretty confusing. "with_for_update" can be method in query, function, bool or dict and it's unclear why we need dict at all. Could we make the code a bit more readable and make it clear why we need for update in one place, but we do not need it in another? I think this all can be achieved by a single bool ("use_for_update") parameter ?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502498460



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1749,62 +1403,353 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if loop_count >= self.num_runs > 0:
+                self.log.info(
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
+                )
+                break
             if self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested DAG parse count (%d) has been reached after %d "
+                    " scheduler loops",
+                    self.num_times_parse_dags, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+          Since creating Dag Runs is a relatively time consuming process, we select only 10 dags by default
+          (configurable via ``scheduler.max_dagruns_to_create_per_loop`` setting) - putting this higher will
+          mean one scheduler could spend a chunk of time creating dag runs, and not ever get around to
+          scheduling tasks.
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default, configurable
+          via ``scheduler.max_dagruns_per_loop_to_schedule`` config setting) and tries to progress state (TIs
+          to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+          The reason we don't select all dagruns at once because the rows are selected with row locks, meaning
+          that only one scheduler can "process them", even it it is waiting behind other dags. Increasing this
+          limit will allow more throughput for smaller DAGs but will likely slow down throughput for larger
+          (>500 tasks.) DAGs
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        # Put a check in place to make sure we don't commit unexpectedly
+        with prohibit_commit(session) as guard:
+
+            if settings.USE_JOB_SCHEDULE:
+                query = DagModel.dags_needing_dagruns(session)
+                self._create_dag_runs(query.all(), session)
+
+                # commit the session - Release the write lock on DagModel table.
+                guard.commit()
+                # END: create dagruns
+
+            dag_runs = DagRun.next_dagruns_to_examine(session)
+
+            # Bulk fetch the currently active dag runs for the dags we are
+            # examining, rather than making one query per DagRun
+
+            # TODO: This query is probably horribly inefficient (though there is an
+            # index on (dag_id,state)). It is to deal with the case when a user
+            # clears more than max_active_runs older tasks -- we don't want the
+            # scheduler to suddenly go and start running tasks from all of the
+            # runs. (AIRFLOW-137/GH #1442)
+            #
+            # The longer term fix would be to have `clear` do this, and put DagRuns
+            # in to the queued state, then take DRs out of queued before creating
+            # any new ones
+            # TODO[HA]: Why is this on TI, not on DagRun??
+            currently_active_runs = dict(session.query(
+                TI.dag_id,
+                func.count(TI.execution_date.distinct()),
+            ).filter(
+                TI.dag_id.in_(list({dag_run.dag_id for dag_run in dag_runs})),
+                TI.state.notin_(State.finished())
+            ).group_by(TI.dag_id).all())
+
+            for dag_run in dag_runs:
+                self._schedule_dag_run(dag_run, currently_active_runs.get(dag_run.dag_id, 0), session)
+
+            guard.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to do it every time?
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.UP_FOR_RETRY],
+                    new_state=State.FAILED,
+                    session=session
+                )
+
+                self._change_state_for_tis_without_dagrun(
+                    old_states=[State.QUEUED,
+                                State.SCHEDULED,
+                                State.UP_FOR_RESCHEDULE,
+                                State.SENSING],
+                    new_state=State.NONE,
+                    session=session
+                )
+
+                guard.commit()
+            except OperationalError as e:
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Lock held by another Scheduler")
+                    session.rollback()
+                else:
+                    raise
+
+            try:
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                if is_lock_not_available_error(error=e):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    session.rollback()
+                    return 0
+                raise
+
+            return num_queued_tis
+
+    def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            dag_hash = self.dagbag.dags_hash.get(dag.dag_id, None)
+            dag.create_dagrun(
+                run_type=DagRunType.SCHEDULED,
+                execution_date=dag_model.next_dagrun,
+                start_date=timezone.utcnow(),
+                state=State.RUNNING,
+                external_trigger=False,
+                session=session,
+                dag_hash=dag_hash
+            )
+
+        self._update_dag_next_dagruns(dag_models, session)
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _update_dag_next_dagruns(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Bulk update the next_dagrun and next_dagrun_create_after for all the dags.
+
+        We batch the select queries to get info about all the dags at once
+        """
+        # Check max_active_runs, to see if we are _now_ at the limit for any of
+        # these dag? (we've just created a DagRun for them after all)
+        active_runs_of_dags = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_([o.dag_id for o in dag_models]),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).group_by(DagRun.dag_id).all())
+
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            active_runs_of_dag = active_runs_of_dags.get(dag.dag_id, 0)
+            if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                    dag.dag_id, active_runs_of_dag, dag.max_active_runs
+                )
+                dag_model.next_dagrun_create_after = None
+            else:
+                dag_model.next_dagrun, dag_model.next_dagrun_create_after = \
+                    dag.next_dagrun_info(dag_model.next_dagrun)
+
+    def _schedule_dag_run(self, dag_run: DagRun, currently_active_runs: int, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        ``currently_active_runs`` is passed in so that a batch query can be
+        used to ask this for all dag runs in the batch, to avoid an n+1 query.
+
+        :param dag_run: The DagRun to schedule
+        :param currently_active_runs: Number of currently active runs of this DAG
+        :return: Number of tasks scheduled
+        """
+        dag = dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if (
+            dag_run.start_date and dag.dagrun_timeout and
+            dag_run.start_date < timezone.utcnow() - dag.dagrun_timeout
+        ):
+            dag_run.state = State.FAILED
+            dag_run.end_date = timezone.utcnow()
+            self.log.info("Run %s of %s has timed-out", dag_run.run_id, dag_run.dag_id)
+            session.flush()
+
+            # Work out if we should allow creating a new DagRun now?
+            self._update_dag_next_dagruns([session.query(DagModel).get(dag_run.dag_id)], session)
+
+            callback_to_execute = DagCallbackRequest(
+                full_filepath=dag.fileloc,
+                dag_id=dag.dag_id,
+                execution_date=dag_run.execution_date,
+                is_failure_callback=True,
+                msg='timed_out'
+            )
+
+            # Send SLA & DAG Success/Failure Callbacks to be executed
+            self._send_dag_callbacks_to_processor(dag_run, callback_to_execute)
+
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        if dag.max_active_runs:
+            if currently_active_runs >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s already has %d active runs, not queuing any more tasks",
+                    dag.dag_id,
+                    currently_active_runs,
+                )
+                return 0
+
+        self._verify_integrity_if_dag_changed(dag_run=dag_run, session=session)
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis, callback_to_run = dag_run.update_state(session=session, execute_callbacks=False)
+
+        self._send_dag_callbacks_to_processor(dag_run, callback_to_run)
+
+        # Get list of TIs that do not need to executed, these are
+        # tasks using DummyOperator and without on_execute_callback / on_success_callback
+        dummy_tis = [
+            ti for ti in schedulable_tis
+            if
+            (
+                ti.task.task_type == "DummyOperator"

Review comment:
       Oh yes. We can't use `isinstance` anymore due to the serialization, unfortunately. Will todo/add an issue shortly.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489378122



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -303,10 +303,10 @@ def done(self) -> bool:
         return False
 
     @property
-    def result(self) -> Optional[Tuple[List[dict], int]]:
+    def result(self) -> Optional[int]:
         """
         :return: result of running SchedulerJob.process_file()
-        :rtype: Optional[Tuple[List[dict], int]]
+        :rtype: int or None

Review comment:
       Doc typing uses a different syntax to type comments https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#info-field-lists:
   
   > Multiple types in a type field will be linked automatically if separated by the word “or”:
   > ```
   > :type an_arg: int or None
   > :vartype a_var: str or int
   > :rtype: float or str
   > ```
   
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492184032



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Right. The context managers look much better here. I understand what you are trying to do. Indeed wee'll have to think about some way of protecting it at static check time rather than at runtime. Since we aren't doing any magical/dynamic stuff here, maybe we could do some custom pylint check and add a @no-commit decorator to functions and then we do this check:
   - @nocommit methods can only call @nocommit methods 
   - @nocommit methods cannot have sessions created - they must be provided
   - @nocommit method cannot call commit()
   - @nocommit method cannot create their own sessions
   
   Is there any other way to issue a commit() - other than auto-closing an automated session and explicit  commit(). If not - that might be much better to check it at static check rather than compile time.
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-705003214


   > The "The job has been cancelled by another workflow." message is slightly confusing -- I'll look at updating that. In this case it's cancelled this PR, because the Build Image workflow failed.
   > 
   > (The reason is there if you can connect the dots, but it's not clear on first glance)
   
   @ashb The problem is that this message comes from the cancelling action which is generic, so I'd have to add an optional "cancel message". Which I will do shortly.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499504292



##########
File path: airflow/models/dag.py
##########
@@ -1824,10 +1960,34 @@ class DagModel(Base):
     # Tags for view filter
     tags = relationship('DagTag', cascade='all,delete-orphan', backref=backref('dag'))
 
+    concurrency = Column(Integer, nullable=False)
+
+    has_task_concurrency_limits = Column(Boolean, nullable=False)
+
+    # The execution_date of the next dag run
+    next_dagrun = Column(UtcDateTime)
+    # Earliest time at which this ``next_dagrun`` can be created
+    next_dagrun_create_after = Column(UtcDateTime)
+
     __table_args__ = (
         Index('idx_root_dag_id', root_dag_id, unique=False),
+        Index('idx_next_dagrun_create_after', next_dagrun_create_after, unique=False),
     )
 
+    NUM_DAGS_PER_DAGRUN_QUERY = conf.getint(
+        'scheduler',
+        'num_dags_needing_dagrun_per_scheduler_loop',
+        fallback=10
+    )

Review comment:
       Let's add this to config file with description what it configures (# of rows to lock?)




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r494807294



##########
File path: airflow/models/dagrun.py
##########
@@ -75,6 +80,8 @@ class DagRun(Base, LoggingMixin):
         backref=backref('dag_run', uselist=False),
     )
 
+    DEFAULT_DAGRUNS_TO_EXAMINE = airflow_conf.getint('scheduler', 'max_dagruns_per_query', fallback=20)

Review comment:
       numbers picked entirely arbitrarily and it seemed to perform well in tests.
   
   The other number is hard coded still because I haven't addressed the to-do comment I already left to pull it out




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489376657



##########
File path: airflow/models/dag.py
##########
@@ -458,6 +458,99 @@ def previous_schedule(self, dttm):
         elif self.normalized_schedule_interval is not None:
             return timezone.convert_to_utc(dttm - self.normalized_schedule_interval)
 
+    def next_dagrun_info(self, date_last_automated_dagrun : Optional[pendulum.DateTime]):
+        """
+        Get information about the next DagRun of this dag after ``date_last_automated_dagrun`` -- the
+        execution date, and the earliest it could be scheduled
+
+        :param date_last_automated_dagrun: The max(execution_date) of existing
+            "automated" DagRuns for this dag (scheduled or backfill, but not
+            manual)
+        """
+        next_execution_date = self.next_dagrun_after_date(date_last_automated_dagrun)
+
+        if next_execution_date is None or self.schedule_interval in (None, '@once'):
+            return None
+
+        return {
+            'execution_date': next_execution_date,
+            'can_be_created_after': self.following_schedule(next_execution_date)
+        }
+
+    def next_dagrun_after_date(self, date_last_automated_dagrun: Optional[pendulum.DateTime]):
+        """
+        Get the next execution date after the given ``date_last_automated_dagrun``, acording to
+        schedule_interval, start_date, end_date etc.  This doesn't check max active run or any other
+        "concurrency" type limits, it only perofmrs calculations based on the varios date and interval fields
+        of this dag and it's tasks.
+
+        :param date_last_automated_dagrun: The execution_date of the last scheduler or
+            backfill triggered run for this dag
+        :type date_last_automated_dagrun: pendulum.Pendulum
+        """
+        if not self.schedule_interval:
+            return None
+
+        # don't schedule @once again
+        if self.schedule_interval == '@once' and date_last_automated_dagrun:
+            return None
+
+        # don't do scheduler catchup for dag's that don't have dag.catchup = True
+        if not (self.catchup or self.schedule_interval == '@once'):
+            # The logic is that we move start_date up until
+            # one period before, so that timezone.utcnow() is AFTER
+            # the period end, and the job can be created...
+            now = timezone.utcnow()
+            next_start = self.following_schedule(now)
+            last_start = self.previous_schedule(now)
+            if next_start <= now or isinstance(self.schedule_interval, timedelta):
+                new_start = last_start
+            else:
+                new_start = self.previous_schedule(last_start)
+
+            if self.start_date:
+                if new_start >= self.start_date:
+                    self.start_date = new_start
+            else:
+                self.start_date = new_start
+
+        next_run_date = None
+        if not date_last_automated_dagrun:
+            # First run
+            task_start_dates = [t.start_date for t in self.tasks]
+            if task_start_dates:
+                next_run_date = self.normalize_schedule(min(task_start_dates))
+                self.log.debug("Next run date based on tasks %s", next_run_date)
+        else:
+            next_run_date = self.following_schedule(date_last_automated_dagrun)
+
+        if date_last_automated_dagrun and next_run_date:
+            while next_run_date <= date_last_automated_dagrun:
+                next_run_date = self.following_schedule(next_run_date)
+
+        # don't ever schedule prior to the dag's start_date
+        if self.start_date:
+            next_run_date = self.start_date if not next_run_date else max(next_run_date, self.start_date)
+            if next_run_date == self.start_date:
+                next_run_date = self.normalize_schedule(self.start_date)
+
+            self.log.debug(
+                "Dag start date: %s. Next run date: %s",
+                self.start_date, next_run_date
+            )
+
+        # Don't schedule a dag beyond its end_date (as specified by the dag param)
+        if next_run_date and self.end_date and next_run_date > self.end_date:
+            return None
+
+        # Don't schedule a dag beyond its end_date (as specified by the task params)
+        # Get the min task end date, which may come from the dag.default_args
+        task_end_dates = [t.end_date for t in self.tasks if t.end_date]
+        if task_end_dates and next_run_date:
+            min_task_end_date = min(task_end_dates)
+            if next_run_date > min_task_end_date:
+                return None
+

Review comment:
       Fixed in 50782a68e




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706313704


   [The Workflow run](https://github.com/apache/airflow/actions/runs/297950829) is cancelling this PR. It has some failed jobs matching ^Pylint$,^Static checks$,^Build docs$,^Spell check docs$,^Backport packages$,^Checks: Helm tests$,^Test OpenAPI*.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499515057



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       I think this one would make a lot of the code cleaner if we do that. Can you elaborate on that?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500417811



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control

Review comment:
       The extra checks on max active runs etc have been added now.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492048248



##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       Can this be a separate PR?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       Seems that "with_for_update of " is missing in 5.7? Seems that in this case TI Aand DR tables both will be locked in this case? I guess it is something that we should also worry about? Seems that in this case we might hit some limitations on parallelism in 5.7.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       Should we separate the DagBag (read_dags_from_db=True) out from the DagBag functionality regarding file reading ? Seems that DagBag(read_dags_from_db=True) is a pass-trought to retrieve Dag via it's Id in a lazy way? 

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Is this something we plan to keep? We seem to catch Exceptions in various places - do we want to actually kill scheduler in this case or just log an error ? 

##########
File path: airflow/executors/base_executor.py
##########
@@ -69,16 +70,16 @@ def start(self):  # pragma: no cover
         """
 
     def queue_command(self,
-                      simple_task_instance: SimpleTaskInstance,

Review comment:
       Good one!




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500602756



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1714,53 +1321,158 @@ def _run_scheduler_loop(self) -> None:
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/ad99ea04b3affba712ad4f36a2908ebd192926c4




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703756198


   Unfortunately, there is no "rerun failed job up to x times" feature in GitHub and this part is a bit outside of our control.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501627191



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       Got it, no strong opinion here but please, add a comment around this line to leave trace to why we do this




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492048248



##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       Can this be a separate PR?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       Seems that "with_for_update of " is missing in 5.7? Seems that in this case TI Aand DR tables both will be locked in this case? I guess it is something that we should also worry about? Seems that in this case we might hit some limitations on parallelism in 5.7.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       Should we separate the DagBag (read_dags_from_db=True) out from the DagBag functionality regarding file reading ? Seems that DagBag(read_dags_from_db=True) is a pass-trought to retrieve Dag via it's Id in a lazy way? 

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Is this something we plan to keep? We seem to catch Exceptions in various places - do we want to actually kill scheduler in this case or just log an error ? 

##########
File path: airflow/executors/base_executor.py
##########
@@ -69,16 +70,16 @@ def start(self):  # pragma: no cover
         """
 
     def queue_command(self,
-                      simple_task_instance: SimpleTaskInstance,

Review comment:
       Good one!

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Right. The context managers look much better here. I understand what you are trying to do. Indeed wee'll have to think about some way of protecting it at static check time rather than at runtime. Since we aren't doing any magical/dynamic stuff here, maybe we could do some custom pylint check and add a @no-commit decorator to functions and then we do this check:
   - @nocommit methods can only call @nocommit methods 
   - @nocommit methods cannot have sessions created - they must be provided
   - @nocommit method cannot call commit()
   - @nocommit method cannot create their own sessions
   
   Is there any other way to issue a commit() - other than auto-closing an automated session and explicit  commit(). If not - that might be much better to check it at static check rather than compile time.
   

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       I see. I still have to wrap my head around the locking consequences here. I understand that here the only locked tables will be TI and DR. the DM is "selectinload"  so likely not locked.
   
   I really just want to understand the consequences and risks. I think a the end we should come up with some "cautious" recommendations to the users. After looking at the potential issues and gains, my current feeling (but needs a bit deeper thinking and testing) is that 
   
   * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you'r adventurous, but expect moderate gains and higher risks of concurrently related problems
   * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems. 
   
   

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       I see. I still have to wrap my head around the locking consequences here. I understand that here the only locked tables will be TI and DR. the DM is "selectinload"  so likely not locked.
   
   I really just want to understand the consequences and risks. I think a the end we should come up with some "cautious" recommendations to the users. After looking at the potential issues and gains, my current feeling (but needs a bit deeper thinking and testing) is that 
   
   * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you're adventurous, but expect moderate gains and higher risks of concurrently related problems
   * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems. 
   
   

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       I see. I still have to wrap my head around the locking consequences here. I understand that here the only locked tables will be TI and DR. the DM is "selectinload"  so likely not locked.
   
   I really just want to understand the consequences and risks. I think a the end we should come up with some "cautious" recommendations to the users. After looking at the potential issues and gains, my current feeling (but needs a bit deeper thinking and testing) is that 
   
   * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you're adventurous, but expect moderate gains and higher risks of concurrency related problems
   * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems. 
   
   

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       Or even `DagDbProxy` - it even can be used by DagBag by composition when needed?
   
   Seems That DagBag(read_dags_from_db=False) is really used for this: `A dagbag is a collection of dags, parsed out of a folder tree` (from the docstring). Then "DagBag(read_dags_from_db=True) is rather used as a proxy to retrieve Dags from teh DB only `get me the DAG with this id from the DB no matter in which folder it is`. 
   
   Sounds like DagBag could use the DagDbProxy when needed and all the places where we create DagBag(read_dags_from_db=True) we could use directly the proxy. That seems to better fit the single-responsibility principle. 

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),

Review comment:
       Yeah. We can remove it later in separate commit.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       Very interesting discussion. I did not have time to pursue it in detail but I will keep an eye on this and see if I can dig a bit deeper here .




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] KevinYang21 commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
KevinYang21 commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491234879



##########
File path: airflow/models/dag.py
##########
@@ -1896,6 +2050,36 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a

Review comment:
       ```suggestion
           Return (and lock) a list of Dag objects that are due to create a new DagRun. This will return a
   ```

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)

Review comment:
       A bit strange that for each round we are creating 10 max dag runs and attempts to examine 20.

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       This is where I'm concerned the most. `update_state` in our use case is very heavy as it requires task dependency checks. In our case there are extreme size DAGs that the dependency checks take minutes--the biggest DAG (20k unique tasks in it) takes >10 mins to check the dependencies for its 3 active DAG runs. It was problematic but in the old world it blocks task scheduling for those DAGs only but if we move it here it will block all task scheduling. Do you mind also elaborate a bit about the reason we want to extract this part from DAG processors and put it in the scheduling loop please?

##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control

Review comment:
       Would you elaborate a bit on the rational behind unconditionally creating a DAG please? Can this break the max_active_runs guarantee? E.g. next_dagrun_create_after is set after the last round of DAG parsing, then someone cleared a couple tasks bringing the DAG run count to its limit, then this part creates another DAG run and no TI will be scheduled for the new DAG runs causing the active DR count stuck above the limit.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502504307



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -868,122 +608,41 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
+            return 0, len(dagbag.import_errors)
 
         try:
             self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Error executing failure callback!")
 
-        # Save individual DAGs in the ORM and update DagModel.last_scheduled_time
+        # Save individual DAGs in the ORM
+        dagbag.read_dags_from_db = True

Review comment:
       Ok. I fount an answer. https://github.com/apache/airflow/pull/10956#discussion_r500572553




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706413435


   We got bored waiting for the Github Actions lottery (build timeouts, 137/OOM kill errors. We did have a green build just before though - https://github.com/apache/airflow/actions/runs/297696260


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499883416



##########
File path: airflow/models/pool.py
##########
@@ -91,7 +96,15 @@ def slots_stats(session: Session = None) -> Dict[str, PoolStats]:
 
         pools: Dict[str, PoolStats] = {}
 
-        pool_rows: Iterable[Tuple[str, int]] = session.query(Pool.pool, Pool.slots).all()
+        query = session.query(Pool.pool, Pool.slots)

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/8f357fdf4630df47d4639706516733e0587480dd




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499630961



##########
File path: airflow/models/dag.py
##########
@@ -1824,10 +1960,34 @@ class DagModel(Base):
     # Tags for view filter
     tags = relationship('DagTag', cascade='all,delete-orphan', backref=backref('dag'))
 
+    concurrency = Column(Integer, nullable=False)
+
+    has_task_concurrency_limits = Column(Boolean, nullable=False)
+
+    # The execution_date of the next dag run
+    next_dagrun = Column(UtcDateTime)
+    # Earliest time at which this ``next_dagrun`` can be created
+    next_dagrun_create_after = Column(UtcDateTime)
+
     __table_args__ = (
         Index('idx_root_dag_id', root_dag_id, unique=False),
+        Index('idx_next_dagrun_create_after', next_dagrun_create_after, unique=False),
     )
 
+    NUM_DAGS_PER_DAGRUN_QUERY = conf.getint(
+        'scheduler',
+        'num_dags_needing_dagrun_per_scheduler_loop',
+        fallback=10
+    )

Review comment:
       Yeah. I think we should keep it documented. I think also some consequences - what we "expect" to happen if we decrease/increase it.  This all can be put in the docs similarly to those comments we have for the other parameter added.
   
   As I see it, changing this number has this behavior (I hope I am interpreting it correctly):
   
   If we decrease it, the scheduling might take longer but have smaller random latency for some Dag Runs. if we have more dags to process in one transaction, it means that there might be a delay in scheduling those dags which are at teh beginning of the batch. However this can decrease the overall "capacity" of the scheduler as batch processing of DagRuns simply uses less resources than processing them one-by-one. There is also less contention possible (do we have other queries/processes that compete for those locks)?  If so then there is a higher chance of those contention locks  happening and then the overall capacity of the system can be impacted by that. Another impact here is that when we have few big dags (in multi-scheduler scenario) that one scheduler will be doing most of the job.
   
   
   Is that correct description? 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489355710



##########
File path: airflow/utils/dag_processing.py
##########
@@ -1037,58 +1028,50 @@ def wait_until_finished(self):
             while not processor.done:
                 time.sleep(0.1)
 
-    def _collect_results_from_processor(self, processor):
+    def _collect_results_from_processor(self, processor) -> None:
         self.log.debug("Processor for %s finished", processor.file_path)
         Stats.decr('dag_processing.processes')
         last_finish_time = timezone.utcnow()
 
         if processor.result is not None:
-            dags, count_import_errors = processor.result
+            count_import_errors = processor.result
         else:
             self.log.error(
                 "Processor for %s exited with return code %s.",
                 processor.file_path, processor.exit_code
             )
-            dags, count_import_errors = [], -1
+            count_import_errors = -1
 
         stat = DagFileStat(
-            num_dags=len(dags),
+            # TODO: Return number of dags, number of errors?
+            num_dags=0,

Review comment:
       Can DagFileProcessor return DAG numbers to use here?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703834310


   [The Build Workflow run](https://github.com/apache/airflow/actions/runs/289987522) is cancelling this PR. The job has been cancelled by another workflow.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492164608



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1052,6 +703,8 @@ def __init__(
         self.max_tis_per_query: int = conf.getint('scheduler', 'max_tis_per_query')
         self.processor_agent: Optional[DagFileProcessorAgent] = None
 
+        self.dagbag = DagBag(read_dags_from_db=True)

Review comment:
       Do you mean have a DbDagBag and a FileDagBag class, or something of that nature?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499643538



##########
File path: airflow/models/dag.py
##########
@@ -1939,6 +2099,37 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs
+        query = session.query(cls).filter(
+            cls.is_paused.is_(False),
+            cls.is_active.is_(True),
+            cls.next_dagrun_create_after <= func.now(),
+        ).order_by(
+            cls.next_dagrun_create_after
+        ).limit(cls.NUM_DAGS_PER_DAGRUN_QUERY)
+
+        return with_for_update(query, of=cls, **skip_locked(session=session))
+
+
+STATICA_HACK = True

Review comment:
       Yeah I know, but there we do it because we had to keep the compatibility with the API, and here it seems that we are doing it here same way but I feel it can be done differently. We will also take a look at that but, this does not seem is the best and most "readable" approach for the "actual code" (not the references to the code from __init__.py ) 
   
   I understand that the problem is that we want to have a non-DAG (in the Directed Acyclic Graph sense) DB model relationships. But I would argue then,  that maybe we want to define those models that are so closely coupled in the same module and use then the technique from https://stackoverflow.com/questions/53842124/sqlalchemy-avoid-cyclic-dependencies-in-orm-without-using-strings (which is what is happening here but the STATIC_HACK would not be needed) - just to reflect their close coupling. I think all the SerializedDag and Dag - they are manifestation of the same "logical" object and having the closely coupled objects together in a single module might simply make sense.
   
   And I am not talking we should do it now. When we reviewed this code, we agreed, that some of further refactoring and separation should be done later - to minimise number of changed/new files, I just wanted to raise the point here that this might be something we want to do very early after that change. Simply this change is mostly about optimisations, which is likely (and does) make the code more complex and intertwined because that's usually the nature of optmisations. But it also increases the complexity of the software and changes meaning of some of the functions and classes (several of the function names, architecture decisions about splitting (or not) the classes that were made some time ago are not valid any more (some of the classes we have more than one responsibility, some of the classes started to share logic from several unrelated now areas and some are split where they should be joined). 
   
   I think if we agree that we should continue our  refactoring after this merge I think I will be fine in deferring this work to the beta iterations.
   
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499650488



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       Just extracting it to separate methods and changing name would make it better. I think (i wrote about it in the other comment) some of the methods and classes lost their original meaning and they do more or less than originally stated. And the only reason for using separate methods and naming them is to give the developer a chance to understand what those methods do without having to read through all the code. So At least an indication that the methods does more than originally intended would be nice. 
   
   I think where it is easy (such as renames/extractions which modern IDEs make super-easy and 0-risk operation), we should try to make the names reflect a bit more the reality. I agree introducing a new class and separating out the responsibility elsewhere might not be a good thing to do now.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ryw edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ryw edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-692908582


   We're working on a short doc that will provide an easy way to test the components/PRs of AIP-15 together, and some preliminary benchmarks for performance improvement, hopefully have that out tomorrow.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r489365115



##########
File path: airflow/utils/dag_processing.py
##########
@@ -1037,58 +1028,50 @@ def wait_until_finished(self):
             while not processor.done:
                 time.sleep(0.1)
 
-    def _collect_results_from_processor(self, processor):
+    def _collect_results_from_processor(self, processor) -> None:
         self.log.debug("Processor for %s finished", processor.file_path)
         Stats.decr('dag_processing.processes')
         last_finish_time = timezone.utcnow()
 
         if processor.result is not None:
-            dags, count_import_errors = processor.result
+            count_import_errors = processor.result
         else:
             self.log.error(
                 "Processor for %s exited with return code %s.",
                 processor.file_path, processor.exit_code
             )
-            dags, count_import_errors = [], -1
+            count_import_errors = -1
 
         stat = DagFileStat(
-            num_dags=len(dags),
+            # TODO: Return number of dags, number of errors?
+            num_dags=0,

Review comment:
       Yes, good idea, I'll change processor to return `(num_dags,num_errors)`




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-702997850


   Instructions to run this PR with docker-compose using CeleryExecutor with Multiple Schedulers:
   
   - Clone the repo and checkout the branch
   
   ```
   git clone --single-branch --branch scheduler-ha-astro https://github.com/astronomer/airflow.git scheduler-ha-airflow
   cd scheduler-ha-airflow
   ```
   
   - Run the docker-compose files:
   
   **Postgres**:
   
   - Run the following command to run the scheduler container (and it's dependencies) that would also take care of running `airflow db upgrade` (creating required tables)
   
   ```
   docker-compose -f docker-compose-postgres.yml run scheduler
   ```
   
   - You can run the above command with `-d` too to run it in background. Or just Ctrl + C after the migrations are run.
   - Scale Up the number of Schedulers to 2 and workers to 4
   
   ```
   docker-compose -f docker-compose-postgres.yml up --scale worker=4 --scale scheduler=2
   ```
   
   **MySQL 8**:
   
   Same as Postgres but no need to specify the docker-compose file as the default is `docker-compose.yml` (which contains MySQL code)
   ```
   docker-compose run scheduler
   ```
   
   - You can run the above command with `-d` too to run it in background. Or just Ctrl + C after the migrations are run.
   - Scale Up the number of Schedulers to 2 and workers to 4
   
   ```
   docker-compose up --scale worker=4 --scale scheduler=2
   ```
   
   **MySQL 5.7**:
   
   ```
   docker-compose -f docker-compose-mysql57.yml up --scale worker=4
   ```
   
   **Note**: Running Multiple Schedulers is not supported with MySQL 5.7. 
   
   You can also try the escape hatch to not use locking mechanism by adding the following environment variable to the docker-compose file:
   
   ```
   AIRFLOW__SCHEDULER__USE_ROW_LEVEL_LOCKING: "False"
   ```
   
   Trigger some example dags from the Webserver (Port: 8080) to see it in action or put your own dags under the `dags` directory (`scheduler-ha-airflow/dags`) -- that directory is mounted on all containers.
   
   Flower UI is exposed on http://localhost:5555/
   
   
   
   ----
   **Troubleshooting**::
   
   If there are any issues (DB Transaction related), try the above instructions again with the following commit:
   
   ```
   git clone --single-branch --branch scheduler-ha-astro https://github.com/astronomer/airflow.git scheduler-ha-airflow
   cd scheduler-ha-airflow
   git checkout 004c2de24
   ```


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb edited a comment on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706331789


   We're trying to get this PR green before merging, because although it doesn't _matter_ we know it's possible and it feels like an important one to say "yes, this is all good" (and we know it's possible to get it green)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706266033


   Man I was _just_ about to merge it too :) I'll squash and rebase it locally.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
kaxil commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-736557250


   > @ashb One more question , how do we custom the number of threads ( that are in practice processes because of the GIL ) of the scheduler ?
   > 
   > there is no more max_threads in http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/latest/configurations-ref.html#scheduler
   > 
   > Thank you
   
   `max_threads` was rename to `parsing_processes` http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/apache-airflow/latest/configurations-ref.html#parsing-processes


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-694789979


   As disucssed with @potiuk , I'll extend this PR to add config option to disable all locking (a.k.a. escape hatch) in case of unforeseen MySQL performance issues. Locking (`SELECT ... FOR UPDATE`) will be on by default, so out of the box on Mysql 8+ and Postgres you can Just Run More Schedulers.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703739157


   [The Build Workflow run](https://github.com/apache/airflow/actions/runs/289727700) is cancelling this PR. The job has been cancelled by another workflow.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703848887


   The "The job has been cancelled by another workflow." message is slightly confusing -- I'll look at updating that. In this case it's cancelled this PR, because the Build Image workflow failed.
   
   (The reason is there if you can connect the dots, but it's not clear on first glance) 


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703754413


   @ashb "Same "unknown blob" if you follow the link and look at the failed job. - I got it also today several times with my personal account so it seems like a transient instability of Github Container Registry. I've not seen it before.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491676262



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       I have some ideas for further optimization of update_state - namely there's no point checking the ti deps of all 20k tasks every time - I think with a bit of thought (taking care of trigger rules etc) we could "prune" whole parts of the graph and not have to check them when the upstream tasks haven't run.
   
   Are you able to share the "shape" of your large dag? (Tasks, triggers etc ). That would help - even if you can do it privately and I can turn it in to a representative test case




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500613827



##########
File path: airflow/config_templates/config.yml
##########
@@ -1562,6 +1562,41 @@
       type: string
       example: ~
       default: "512"
+    - name: use_row_level_locking
+      description: |
+        Should the scheduler issue `SELECT ... FOR UPDATE` in relevant queries.
+        If this is set to False then you should not run more than a single
+        scheduler at once
+      version_added: 2.0.0
+      type: boolean
+      example: ~
+      default: "True"
+    - name: max_dagruns_to_create_per_loop
+      description: |
+        This changes the number of dags that are locked by each scheduler when
+        creating dag runs. One possible reason for setting this lower is if you
+        have huge dags and are running multiple schedules, you won't want one
+        scheduler to do all the work.
+
+        Default: 10
+      example: ~
+      version_added: 2.0.0
+      type: string
+      default: ~
+    - name: max_dagruns_per_loop_to_schedule
+      description: |
+        How many DagRuns should a scheduler exaimne (and lock) when scheduling
+        and queuing tasks. Increasing this limit will allow more throughput for
+        smaller DAGs but will likely slow down throughput for larger (>500
+        tasks for example.) DAGs. Setting this to high when using multiple

Review comment:
       I know it 👌 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] github-actions[bot] commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-703727428


   The CI and PROD Docker Images for the build are prepared in a separate "Build Image" workflow,
   that you will not see in the list of checks (you will see "Wait for images" jobs instead).
   
   You can checks the status of those images in [The workflow run](https://github.com/apache/airflow/actions/runs/289727700)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
kaxil commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706262452


   ![Press the Button](https://media.giphy.com/media/3o75279fBGgbO848ZW/giphy.gif)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ryw edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ryw edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-692908582


   We're working on a short doc that will provide an easy way to test all the components/PRs of AIP-15 together, and some preliminary benchmarks for performance improvement, hopefully have that out tomorrow.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk edited a comment on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
potiuk edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706258940


   > Still fewer comments than #4938
   
   I am afraid @mik-laj beat me already with #8721, so you are not even close to  the podium @ashb 


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r490827114



##########
File path: airflow/models/dag.py
##########
@@ -458,6 +458,101 @@ def previous_schedule(self, dttm):
         elif self.normalized_schedule_interval is not None:
             return timezone.convert_to_utc(dttm - self.normalized_schedule_interval)
 
+    def next_dagrun_info(self, date_last_automated_dagrun : Optional[pendulum.DateTime]):
+        """
+        Get information about the next DagRun of this dag after ``date_last_automated_dagrun`` -- the
+        execution date, and the earliest it could be scheduled
+
+        :param date_last_automated_dagrun: The max(execution_date) of existing
+            "automated" DagRuns for this dag (scheduled or backfill, but not
+            manual)
+        """
+        next_execution_date = self.next_dagrun_after_date(date_last_automated_dagrun)
+
+        if next_execution_date is None or self.schedule_interval in (None, '@once'):
+            return None
+
+        return {
+            'execution_date': next_execution_date,
+            'can_be_created_after': self.following_schedule(next_execution_date)
+        }

Review comment:
       Nice idea, will do.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499494587



##########
File path: airflow/models/dag.py
##########
@@ -1572,6 +1661,21 @@ def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
             session.add(orm_dag)
             orm_dags.append(orm_dag)
 
+        # Get the latest dag run for each existing dag as a single query (avoid n+1 query)
+        most_recent_dag_runs = dict(session.query(DagRun.dag_id, func.max_(DagRun.execution_date)).filter(
+            DagRun.dag_id.in_(existing_dag_ids),
+            or_(
+                DagRun.run_type == DagRunType.BACKFILL_JOB.value,
+                DagRun.run_type == DagRunType.SCHEDULED.value,
+            ),
+        ).group_by(DagRun.dag_id).all())
+
+        num_active_runs = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_(existing_dag_ids),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False)
+        ).group_by(DagRun.dag_id).all())

Review comment:
       I wonder if it should be done in this method.  This method only talks about data synchronization, not updating other fields.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r490087759



##########
File path: airflow/utils/dag_processing.py
##########
@@ -1037,58 +1028,50 @@ def wait_until_finished(self):
             while not processor.done:
                 time.sleep(0.1)
 
-    def _collect_results_from_processor(self, processor):
+    def _collect_results_from_processor(self, processor) -> None:
         self.log.debug("Processor for %s finished", processor.file_path)
         Stats.decr('dag_processing.processes')
         last_finish_time = timezone.utcnow()
 
         if processor.result is not None:
-            dags, count_import_errors = processor.result
+            count_import_errors = processor.result
         else:
             self.log.error(
                 "Processor for %s exited with return code %s.",
                 processor.file_path, processor.exit_code
             )
-            dags, count_import_errors = [], -1
+            count_import_errors = -1
 
         stat = DagFileStat(
-            num_dags=len(dags),
+            # TODO: Return number of dags, number of errors?
+            num_dags=0,

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/edaa101c60af4b5ec459ac75534da177ccf753ff




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499545844



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       I have doubts about this method:
   1. Is the name of this method still correct? `bulk_sync_to_db_and_precompute_fields`?
   2. Can a new code not be extracted into new methods/classes?  `SchedulerPredictor`?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] pingzh commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
pingzh commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502694216



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       @ashb I did try to cherry pick this pr to our internal repo,, which is based on 1.10.4: https://github.com/apache/airflow/pull/4751, (https://github.com/apache/airflow/pull/11010 for 1.10 branch) and https://github.com/apache/airflow/pull/7503. However, the overall performance actually increased. I have not found the root cause. It could be due to our optimization at the deps check with `ThreadPool`, which made if faster to do the deps check.
   
   ```
   # this loop is quite slow as it uses are_dependencies_met for
   # every task (in ti.is_runnable). This is also called in
   # update_state above which has already checked these tasks
   @provide_session
   def enqueue_task_if_deps_met(ti, session=None):
       task = dag.get_task(ti.task_id)
   
       # fixme: ti.task is transient but needs to be set
       ti.task = task
   
       if ti.are_dependencies_met(
               dep_context=DepContext(flag_upstream_failed=True),
               session=session, early_exit_on_failed_dep=True):
           self.log.debug('Queuing task: %s', ti)
           return ti.key
       return None
   
   with ThreadPoolExecutor(max_workers=50) as executor:
       for ti_key in filter(lambda x: x is not None, executor.map(enqueue_task_if_deps_met, tis)):
           task_instances_list.append(ti_key)
   
   ```
   
   I think in general we should move to non blocking fashion to increase the throughput of the scheduler.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491323370



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control

Review comment:
       Unconditional here as the checks are done elsewhere/at the caller.
   
   I'll double check the case you mention - I think it's already covered in the unit tests too




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502503273



##########
File path: airflow/models/dag.py
##########
@@ -1572,6 +1661,21 @@ def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
             session.add(orm_dag)
             orm_dags.append(orm_dag)
 
+        # Get the latest dag run for each existing dag as a single query (avoid n+1 query)
+        most_recent_dag_runs = dict(session.query(DagRun.dag_id, func.max_(DagRun.execution_date)).filter(
+            DagRun.dag_id.in_(existing_dag_ids),
+            or_(
+                DagRun.run_type == DagRunType.BACKFILL_JOB.value,
+                DagRun.run_type == DagRunType.SCHEDULED.value,
+            ),
+        ).group_by(DagRun.dag_id).all())
+
+        num_active_runs = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_(existing_dag_ids),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False)
+        ).group_by(DagRun.dag_id).all())

Review comment:
       LGTM




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491298914



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)

Review comment:
       These numbers were chosen somewhat randomly, but on the assumption that a few runs are created (and creating them "slowly" - but still faster than before, is fine) but that if there are more running runs, that we should examine them 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-699892472


   > For anyone review by this, the code is pretty feature complete now - there are only a few unit tests left to fix up due to the changed code.
   > 
   > The existing unit tests were surprisingly comprehensive and caught a couple of small logic bugs/missing features, which is encouraging
   
   We will resume looking at it tomorrow when @turbaszek comes back - we found that joint review sessions work best for this kind of changes.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r498315428



##########
File path: airflow/config_templates/config.yml
##########
@@ -1547,6 +1547,15 @@
       type: string
       example: ~
       default: "512"
+    - name: use_row_level_locking
+      description: |
+        Should the scheduler issue `SELECT ... FOR UPDATE` in relevant queries.

Review comment:
       :heart: 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] raphaelauv commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
raphaelauv commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-735450124


   @ashb is this mean the localExecutor is now thread-safe in the use of pools ? 
   
   https://airflow.apache.org/docs/stable/concepts.html#pools
   
   `Pools are not thread-safe , in case of more than one scheduler in localExecutor Mode you can’t ensure the non-scheduling of task even if the pool is full.
   `


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499646376



##########
File path: airflow/models/dagrun.py
##########
@@ -94,8 +103,14 @@ def __init__(
         self.conf = conf or {}
         self.state = state
         self.run_type = run_type
+        self.dag_hash = dag_hash
+        self.callback: Optional[callback_requests.DagCallbackRequest] = None

Review comment:
       I think that's the easiest way - if we add type checking it's not even bad (and actually maybe we can also find a better name for the update_state method which we wrote about elsewhere. The update_state is not a really good name now as this method does more than that. 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r501238709



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -899,122 +667,54 @@ def process_file(
         except Exception:  # pylint: disable=broad-except
             self.log.exception("Failed at reloading the DAG file %s", file_path)
             Stats.incr('dag_file_refresh_error', 1, 1)
-            return [], 0
+            return 0, 0
 
         if len(dagbag.dags) > 0:
             self.log.info("DAG(s) %s retrieved from %s", dagbag.dags.keys(), file_path)
         else:
             self.log.warning("No viable dags retrieved from %s", file_path)
             self.update_import_errors(session, dagbag)
-            return [], len(dagbag.import_errors)
-
-        try:
-            self.execute_on_failure_callbacks(dagbag, failure_callback_requests)
-        except Exception:  # pylint: disable=broad-except
-            self.log.exception("Error executing failure callback!")
-
-        # Save individual DAGs in the ORM and update DagModel.last_scheduled_time
-        dagbag.sync_to_db()
-
-        paused_dag_ids = DagModel.get_paused_dag_ids(dag_ids=dagbag.dag_ids)
-
-        unpaused_dags: List[DAG] = [
-            dag for dag_id, dag in dagbag.dags.items() if dag_id not in paused_dag_ids
-        ]
-
-        serialized_dags = self._prepare_serialized_dags(unpaused_dags, pickle_dags, session)
+            return 0, len(dagbag.import_errors)
+
+        self.execute_callbacks(dagbag, callback_requests)
+
+        # Save individual DAGs in the ORM
+        dagbag.read_dags_from_db = True
+
+        # Retry 'dagbag.sync_to_db()' in case of any Operational Errors
+        # In case of failures, provide_session handles rollback
+        for attempt in tenacity.Retrying(
+            retry=tenacity.retry_if_exception_type(exception_types=OperationalError),
+            wait=tenacity.wait_random_exponential(multiplier=0.5, max=5),
+            stop=tenacity.stop_after_attempt(settings.MAX_DB_RETRIES),
+            before_sleep=tenacity.before_sleep_log(self.log, logging.DEBUG),
+            reraise=True
+        ):
+            with attempt:
+                self.log.debug(
+                    "Running dagbag.sync_to_db with retries. Try %d of %d",
+                    attempt.retry_state.attempt_number,
+                    settings.MAX_DB_RETRIES
+                )
+                dagbag.sync_to_db()
 
-        dags = self._find_dags_to_process(unpaused_dags)
+        if pickle_dags:
+            paused_dag_ids = DagModel.get_paused_dag_ids(dag_ids=dagbag.dag_ids)
 
-        ti_keys_to_schedule = self._process_dags(dags, session)
+            unpaused_dags: List[DAG] = [
+                dag for dag_id, dag in dagbag.dags.items() if dag_id not in paused_dag_ids
+            ]
 
-        self._schedule_task_instances(dagbag, ti_keys_to_schedule, session)
+            for dag in unpaused_dags:
+                dag.pickle(session)

Review comment:
       This may be more effective as we are not using `unpaused_dags` anywhere else than this loop.
   ```python
   for dag_id, dag in dagbag.dags.items():
       if dag_id not in paused_dag_ids:
           dag.pickle(session)
   ```
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491470766



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       Out of interest how does the browser cope with displaying such a large dag (ignoring webserver boot up time)




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499535867



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:

Review comment:
       ```suggestion
               if loop_count >= self.num_runs > 0:
   ```
   WDYT?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-702041010


   > > This PR (with 2 Schedulers)
   > > TI Lag Avg: 74.028s (± 17.215)
   > > Time in Queued State: 68.708s (± 15.556)
   > 
   > Is the last measurement correct?
   
   Yeah. Looks like copy&paste error from 1.10.10 ? 


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500096812



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -556,12 +556,15 @@ def execute_callbacks(
         :param session: DB session.
         """
         for request in callback_requests:
-            if isinstance(request, TaskCallbackRequest):
-                self._execute_task_callbacks(dagbag, request)
-            elif isinstance(request, SlaCallbackRequest):
-                self.manage_slas(dagbag.dags.get(request.dag_id))
-            elif isinstance(request, DagCallbackRequest):
-                self._execute_dag_callbacks(dagbag, request, session)
+            try:
+                if isinstance(request, TaskCallbackRequest):
+                    self._execute_task_callbacks(dagbag, request)
+                elif isinstance(request, SlaCallbackRequest):
+                    self.manage_slas(dagbag.dags.get(request.dag_id))

Review comment:
       I think `manage_slas` is fine being public since you can run perform some actions and tests outside of the Scheduler too. The only reason it is not a static method is because we use self.log




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492163936



##########
File path: airflow/jobs/backfill_job.py
##########
@@ -629,6 +629,7 @@ def _per_task_process(task, key, ti, session=None):  # pylint: disable=too-many-
             _dag_runs = ti_status.active_runs[:]
             for run in _dag_runs:
                 run.update_state(session=session)
+                session.merge(run)

Review comment:
       It is, yes, but I can do this better
   
   In [dagrun.py](https://github.com/apache/airflow/pull/10956/files#diff-32aa8dbb910719ef24a39cab5d0f2a97L376-L379) I removed the commit (on purpose) but also removed the merge by mistake:
   
   ```diff
   -        # todo: determine we want to use with_for_update to make sure to lock the run
   -        session.merge(self)
   -        session.commit()
   -
   ```
   
   ->
   
   
   ```diff
   -        # todo: determine we want to use with_for_update to make sure to lock the run
           session.merge(self)
   -        session.commit()
   -
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-694769676


   I'm working on updating/adding to the tests -- this fixup commit is going to be a bit large I'm afraid (at +444/-406 so far, about 60% through) -- as many tests have been re-organized between TestDagFileProcessor and TestSchedulerJob to reflect the location of new code (for example, `test_dag_with_system_exit` doesn't make sense in TestSchedulerJob anymore, as the scheduler doesn't parse the dags at all)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] mik-laj commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492161940



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       nit: we can create a context manager that will make sure that the transaction is not committed in the code block.
   ```python
   with keep_traansaction():
        ....
   ```
   ```python
   with prohibit_commit():
        ....
   ```
   The effect will be the same, but the intention will be easier to understand.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706218673


   @potiuk @mik-laj @turbaszek I think we've addressed all your comments now.
   
   Would you like to review it again (or just look at the changes) before or after we rebase to squash all the fixup commits?


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r492188003



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1179,39 +832,50 @@ def __get_concurrency_maps(
 
     # pylint: disable=too-many-locals,too-many-statements
     @provide_session
-    def _find_executable_task_instances(
-        self,
-        simple_dag_bag: SimpleDagBag,
-        session: Session = None
-    ) -> List[TI]:
+    def _executable_task_instances_to_queued(self, max_tis: int, session: Session = None) -> List[TI]:
         """
         Finds TIs that are ready for execution with respect to pool limits,
         dag concurrency, executor state, and priority.
 
-        :param simple_dag_bag: TaskInstances associated with DAGs in the
-            simple_dag_bag will be fetched from the DB and executed
-        :type simple_dag_bag: airflow.utils.dag_processing.SimpleDagBag
+        :param max_tis: Maximum number of TIs to queue in this loop.
+        :type max_tis: int
         :return: list[airflow.models.TaskInstance]
         """
         executable_tis: List[TI] = []
 
+        # Get the pool settings. We get a lock on the pool rows, treating this as a "critical section"
+        # Throws an exception if lock cannot be obtained, rather than blocking
+        pools = models.Pool.slots_stats(with_for_update=nowait(session), session=session)
+
+        # If the pools are full, there is no point doing anything!
+        # If _somehow_ the pool is overfull, don't let the limit go negative - it breaks SQL
+        pool_slots_free = max(0, sum(map(operator.itemgetter('open'), pools.values())))
+
+        if pool_slots_free == 0:
+            self.log.debug("All pools are full!")
+            return executable_tis
+
+        max_tis = min(max_tis, pool_slots_free)
+
         # Get all task instances associated with scheduled
         # DagRuns which are not backfilled, in the given states,
         # and the dag is not paused
         task_instances_to_examine: List[TI] = (
             session
             .query(TI)
-            .filter(TI.dag_id.in_(simple_dag_bag.dag_ids))
-            .outerjoin(
-                DR, and_(DR.dag_id == TI.dag_id, DR.execution_date == TI.execution_date)
-            )
-            .filter(or_(DR.run_id.is_(None), DR.run_type != DagRunType.BACKFILL_JOB.value))
-            .outerjoin(DM, DM.dag_id == TI.dag_id)
-            .filter(or_(DM.dag_id.is_(None), not_(DM.is_paused)))
+            .outerjoin(TI.dag_run)
+            .filter(or_(DR.run_id.is_(None),
+                        DR.run_type != DagRunType.BACKFILL_JOB.value))
+            .join(TI.dag_model)
+            .filter(not_(DM.is_paused))
             .filter(TI.state == State.SCHEDULED)
+            .options(selectinload('dag_model'))
+            .limit(max_tis)
+            .with_for_update(of=TI, **skip_locked(session=session))

Review comment:
       I see. I still have to wrap my head around the locking consequences here. I understand that here the only locked tables will be TI and DR. the DM is "selectinload"  so likely not locked.
   
   I really just want to understand the consequences and risks. I think a the end we should come up with some "cautious" recommendations to the users. After looking at the potential issues and gains, my current feeling (but needs a bit deeper thinking and testing) is that 
   
   * MySQL 5.7 -> go with 1 scheduler (and escape hatch if possible/easy to implement). Experiment if you're adventurous, but expect moderate gains and higher risks of concurrently related problems
   * MySQL 8 -> should work fine and bring expected gains, with much lower risk of concurrency problems. 
   
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-702097998


   > > > This PR (with 2 Schedulers)
   > > > TI Lag Avg: 74.028s (± 17.215)
   > > > Time in Queued State: 68.708s (± 15.556)
   > > 
   > > 
   > > Is the last measurement correct?
   > 
   > Whoops yeah updated **Time in Queued State: 751.241s (± 35.5153)** for 1.10.10
   
   Coool!


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-699899853


   I'm happy to help explain any of my design decisions too - either on a call, or you can leave a comment here, and then either way I will leave comments/docs in the code.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499878674



##########
File path: airflow/utils/sqlalchemy.py
##########
@@ -141,3 +142,107 @@ def skip_locked(session: Session) -> Dict[str, Any]:
         return {'skip_locked': True}
     else:
         return {}
+
+
+def nowait(session: Session) -> Dict[str, Any]:
+    """
+    Return kwargs for passing to `with_for_update()` suitable for the current DB engine version.
+
+    We do this as we document the fact that on DB engines that don't support this construct, we do not
+    support/recommend running HA scheduler. If a user ignores this and tries anyway everything will still
+    work, just slightly slower in some circumstances.
+
+    Specifically don't emit NOWAIT for MySQL < 8, or MariaDB, neither of which support this construct
+
+    See https://jira.mariadb.org/browse/MDEV-13115
+    """
+    dialect = session.bind.dialect
+
+    if dialect.name != "mysql" or dialect.supports_for_update_of:
+        return {'nowait': True}
+    else:
+        return {}
+
+
+def nulls_first(col, session: Session) -> Dict[str, Any]:
+    """
+    Adds a nullsfirst construct to the column ordering. Currently only Postgres supports it.
+    In MySQL & Sqlite NULL values are considered lower than any non-NULL value, therefore, NULL values
+    appear first when the order is ASC (ascending)
+    """
+    if session.bind.dialect.name == "postgresql":
+        return nullsfirst(col)
+    else:
+        return col
+
+
+USE_ROW_LEVEL_LOCKING: bool = conf.getboolean('scheduler', 'use_row_level_locking', fallback=True)
+
+
+def with_for_update(query, **kwargs):

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/8f357fdf4630df47d4639706516733e0587480dd




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb edited a comment on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb edited a comment on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-699455633


   For anyone review by this, the code is pretty feature complete now - there are only a few unit tests left to fix up due to the changed code.
   
   The existing unit tests were surprisingly comprehensive and caught a couple of small logic bugs/missing features, which is encouraging


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-700530503


   > I did indeed. For some reason (I thought sqlite was the default. I blame working late)
   
   It is the default, but breeze also persistently stores a few of the selections you've made last time (python version, database, dosckerhub user etc._ so that you do not have to add switches every time you run it. Simply running "breeze" will drop you to the environment you used last time.
   
   And it prints summary of those when you enter:
   
   ```
                                 Use CI image.
   
                                  Branch name:            master
                                  Docker image:           apache/airflow:master-python3.6-ci
                                  Airflow source version: 2.0.0.dev0
                                  Python version:         3.6
                                  DockerHub user:         apache
                                  DockerHub repo:         airflow
                                  Backend:                sqlite 
   
   Airflow core SQL connection: sqlite:////root/airflow/airflow.db
   ```
   
   Also what helps, you can run `toggle-suppress-cheatsheet` and `breeze toggle-suppress-asciiart` to permanently disable both cheatsheet and the asciiart and they it will only show the "environment summary" when you enter  - this is easier to see it then.


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r502389807



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1050,23 +754,17 @@ class SchedulerJob(BaseJob):  # pylint: disable=too-many-instance-attributes
 
     def __init__(
             self,
-            dag_id: Optional[str] = None,
-            dag_ids: Optional[List[str]] = None,
             subdir: str = settings.DAGS_FOLDER,
             num_runs: int = conf.getint('scheduler', 'num_runs'),
+            num_times_parse_dags: int = -1,

Review comment:
       Added in d09c846d9 




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
kaxil commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706261391


   My approval shouldn't count here, but oh well 😄  


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] dimberman commented on pull request #10956: Fully support running more than one scheduler concurrently

Posted by GitBox <gi...@apache.org>.
dimberman commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-706262031


   @kaxil mine neither, I just wanted a record that I was here :)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500609846



##########
File path: airflow/models/dag.py
##########
@@ -1573,34 +1680,28 @@ def create_dagrun(self,
 
     @classmethod
     @provide_session
-    def bulk_sync_to_db(cls, dags: Collection["DAG"], sync_time=None, session=None):
+    def bulk_sync_to_db(cls, dags: Collection["DAG"], session=None):

Review comment:
       I think we should change the name, I agree with Kamil and Jarek that it now does a bit more than just "sync_to_db" which for me is like flushing current state to DB.
   
   Maybe `bulk_sync_to_db_and_set_next_dagrun` ? and we could extract the statements that set next dag run to a separate method (`_set_next_dag_run`) that is called from this method.
   
   
   




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] potiuk commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499517257



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")

Review comment:
       Looks Good!




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499491362



##########
File path: airflow/models/dagbag.py
##########
@@ -510,6 +513,6 @@ def sync_to_db(self):
         DAG.bulk_sync_to_db(self.dags.values())
         # Write Serialized DAGs to DB if DAG Serialization is turned on
         # Even though self.read_dags_from_db is False
-        if settings.STORE_SERIALIZED_DAGS:
+        if settings.STORE_SERIALIZED_DAGS or self.read_dags_from_db:

Review comment:
       @ashb can you please take a look here?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r491321471



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1705,62 +1305,216 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
-            if self.processor_agent.done:
+            if self.num_runs > 0 and loop_count >= self.num_runs and self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        try:
+            from sqlalchemy import event
+            expected_commit = False
+
+            # Put a check in place to make sure we don't commit unexpectedly
+            @event.listens_for(session.bind, 'commit')
+            def validate_commit(_):
+                nonlocal expected_commit
+                if expected_commit:
+                    expected_commit = False
+                    return
+                raise RuntimeError("UNEXPECTED COMMIT - THIS WILL BREAK HA LOCKS!")
+
+            query = DagModel.dags_needing_dagruns(session)
+            for dag_model in query:
+                dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+                self._create_dag_run(dag_model, dag, session)
+
+            # commit the session - Release the write lock on DagModel table.
+            expected_commit = True
+            session.commit()
+            # END: create dagruns
+
+            for dag_run in DagRun.next_dagruns_to_examine(session):
+                self._schedule_dag_run(dag_run, session)
+
+            expected_commit = True
+            session.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    return 0
+                raise
+
+            return num_queued_tis
+        finally:
+            event.remove(session.bind, 'commit', validate_commit)
+
+    def _create_dag_run(self, dag_model: DagModel, dag: DAG, session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        next_run_date = dag_model.next_dagrun
+        dag.create_dagrun(
+            run_type=DagRunType.SCHEDULED,
+            execution_date=next_run_date,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            external_trigger=False,
+            session=session
         )
-        self._execute_task_instances(simple_dag_bag)
+
+        # Check max_active_runs, to see if we are _now_ at the limit for this dag? (we've just created
+        # one after all)
+        active_runs_of_dag = session.query(func.count('*')).filter(
+            DagRun.dag_id == dag_model.dag_id,
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).scalar()
+
+        # TODO[HA]: add back in dagrun.timeout
+
+        if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+            self.log.info(
+                "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                dag.dag_id, active_runs_of_dag, dag.max_active_runs
+            )
+            dag_model.next_dagrun = None
+            dag_model.next_dagrun_create_after = None
+        else:
+            next_dagrun_info = dag.next_dagrun_info(next_run_date)
+            if next_dagrun_info:
+                dag_model.next_dagrun = next_dagrun_info['execution_date']
+                dag_model.next_dagrun_create_after = next_dagrun_info['can_be_created_after']
+            else:
+                dag_model.next_dagrun = None
+                dag_model.next_dagrun_create_after = None
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _schedule_dag_run(self, dag_run: DagRun, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        :return: Number of tasks scheduled
+        """
+        dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag_run.dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag_run.dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        # TODO: This query is probably horribly inefficient (though there is an
+        # index on (dag_id,state)). It is to deal with the case when a user
+        # clears more than max_active_runs older tasks -- we don't want the
+        # scheduler to suddenly go and start running tasks from all of the
+        # runs. (AIRFLOW-137/GH #1442)
+        #
+        # The longer term fix would be to have `clear` do this, and put DagRuns
+        # in to the queued state, then take DRs out of queued before creating
+        # any new ones
+        if dag_run.dag.max_active_runs:
+            currently_active_runs = session.query(func.count(TI.execution_date.distinct())).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.state.notin_(State.finished())
+            ).scalar()
+
+            if currently_active_runs >= dag_run.dag.max_active_runs:
+                return 0
+
+        # TODO[HA]: Run verify_integrity, but only if the serialized_dag has changed
+
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session)

Review comment:
       I'll respond fuller later, and run tests with a huge dag like you talk about, but I wonder if https://github.com/apache/airflow/pull/4751 has already massively improved that problem.
   
   The cliff notes version: one of the major bottlenecks when having 100s or 1000s of dags was waiting for the parsing process to come around to the file again before the next task in a day could be scheduled.
   
   Additional hitting the dag processor timeout (introduced/actually enforced in 1.10.4) could lead to a situation where a dag becomes permanently unschedulable: if it timesout (usually due to accumulating load/too many active dag runs, etc.) then that dag is never returned to the scheduler, and tasks in that day will never be eligible to be queued in the previous implementation - this has been surprising and hidden/hard to debug problem for many users causing production outages.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499708313



##########
File path: airflow/jobs/scheduler_job.py
##########
@@ -1706,62 +1342,326 @@ def _run_scheduler_loop(self) -> None:
             loop_duration = loop_end_time - loop_start_time
             self.log.debug("Ran scheduling loop in %.2f seconds", loop_duration)
 
-            if not is_unit_test:
+            if not is_unit_test and not num_queued_tis and not num_finished_events:
+                # If the scheduler is doing things, don't sleep. This means when there is work to do, the
+                # scheduler will run "as quick as possible", but when it's stopped, it can sleep, dropping CPU
+                # usage when "idle"
                 time.sleep(self._processor_poll_interval)
 
+            if self.num_runs > 0 and loop_count >= self.num_runs:
+                self.log.info(
+                    "Exiting scheduler loop as requested number of runs (%d - got to %d) has been reached",
+                    self.num_runs, loop_count,
+                )
+                break
             if self.processor_agent.done:
                 self.log.info(
-                    "Exiting scheduler loop as all files have been processed %d times", self.num_runs
+                    "Exiting scheduler loop as requested DAG parse count (%d) has been reached after %d "
+                    " scheduler loops",
+                    self.num_times_parse_dags, loop_count,
                 )
                 break
 
-    def _validate_and_run_task_instances(self, simple_dag_bag: SimpleDagBag) -> bool:
-        if simple_dag_bag.serialized_dags:
+    def _do_scheduling(self, session) -> int:
+        """
+        This function is where the main scheduling decisions take places. It:
+
+        - Creates any necessary DAG runs by examining the next_dagrun_create_after column of DagModel
+
+        - Finds the "next n oldest" running DAG Runs to examine for scheduling (n=20 by default) and tries to
+          progress state (TIs to SCHEDULED, or DagRuns to SUCCESS/FAILURE etc)
+
+          By "next oldest", we mean hasn't been examined/scheduled in the most time.
+
+        - Then, via a Critical Section (locking the rows of the Pool model) we queue tasks, and then send them
+          to the executor.
+
+          See docs of _critical_section_execute_task_instances for more.
+
+        :return: Number of TIs enqueued in this iteration
+        :rtype: int
+        """
+        # Put a check in place to make sure we don't commit unexpectedly
+        with prohibit_commit(session) as guard:
+
+            query = DagModel.dags_needing_dagruns(session)
+            self._create_dag_runs(query.all(), session)
+
+            # commit the session - Release the write lock on DagModel table.
+            guard.commit()
+            # END: create dagruns
+
+            dag_runs = DagRun.next_dagruns_to_examine(session)
+
+            # Bulk fetch the currently active dag runs for the dags we are
+            # examining, rather than making one query per DagRun
+
+            # TODO: This query is probably horribly inefficient (though there is an
+            # index on (dag_id,state)). It is to deal with the case when a user
+            # clears more than max_active_runs older tasks -- we don't want the
+            # scheduler to suddenly go and start running tasks from all of the
+            # runs. (AIRFLOW-137/GH #1442)
+            #
+            # The longer term fix would be to have `clear` do this, and put DagRuns
+            # in to the queued state, then take DRs out of queued before creating
+            # any new ones
+            # TODO[HA]: Why is this on TI, not on DagRun??
+            currently_active_runs = dict(session.query(
+                TI.dag_id,
+                func.count(TI.execution_date.distinct()),
+            ).filter(
+                TI.dag_id.in_(list({dag_run.dag_id for dag_run in dag_runs})),
+                TI.state.notin_(State.finished())
+            ).group_by(TI.dag_id).all())
+
+            for dag_run in dag_runs:
+                self._schedule_dag_run(dag_run, currently_active_runs.get(dag_run.dag_id, 0), session)
+
+            guard.commit()
+
+            # Without this, the session has an invalid view of the DB
+            session.expunge_all()
+            # END: schedule TIs
+
+            # TODO[HA]: Do we need to call
+            # _change_state_for_tis_without_dagrun (2x) that we were before
+            # to tidy up manually tweaked TIs. Do we need to do it every
+            # time?
+
             try:
-                self._process_and_execute_tasks(simple_dag_bag)
-            except Exception as e:  # pylint: disable=broad-except
-                self.log.error("Error queuing tasks")
-                self.log.exception(e)
-                return False
-
-        # Call heartbeats
-        self.log.debug("Heartbeating the executor")
-        self.executor.heartbeat()
-
-        self._change_state_for_tasks_failed_to_execute()
-
-        # Process events from the executor
-        self._process_executor_events(simple_dag_bag)
-        return True
-
-    def _process_and_execute_tasks(self, simple_dag_bag: SimpleDagBag) -> None:
-        # Handle cases where a DAG run state is set (perhaps manually) to
-        # a non-running state. Handle task instances that belong to
-        # DAG runs in those states
-        # If a task instance is up for retry but the corresponding DAG run
-        # isn't running, mark the task instance as FAILED so we don't try
-        # to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.UP_FOR_RETRY],
-            new_state=State.FAILED
-        )
-        # If a task instance is scheduled or queued or up for reschedule,
-        # but the corresponding DAG run isn't running, set the state to
-        # NONE so we don't try to re-run it.
-        self._change_state_for_tis_without_dagrun(
-            simple_dag_bag=simple_dag_bag,
-            old_states=[State.QUEUED,
-                        State.SCHEDULED,
-                        State.UP_FOR_RESCHEDULE,
-                        State.SENSING],
-            new_state=State.NONE
+                if self.executor.slots_available <= 0:
+                    # We know we can't do anything here, so don't even try!
+                    self.log.debug("Executor full, skipping critical section")
+                    return 0
+
+                timer = Stats.timer('scheduler.critical_section_duration')
+                timer.start()
+
+                # Find anything TIs in state SCHEDULED, try to QUEUE it (send it to the executor)
+                num_queued_tis = self._critical_section_execute_task_instances(session=session)
+
+                # Make sure we only sent this metric if we obtained the lock, otherwise we'll skew the
+                # metric, way down
+                timer.stop(send=True)
+            except OperationalError as e:
+                timer.stop(send=False)
+
+                # DB specific error codes:
+                # Postgres: 55P03
+                # MySQL: 3572, 'Statement aborted because lock(s) could not be acquired immediately and NOWAIT
+                #               is set.'
+                # MySQL: 1205, 'Lock wait timeout exceeded; try restarting transaction
+                #              (when NOWAIT isn't available)
+                db_err_code = getattr(e.orig, 'pgcode', None) or e.orig.args[0]
+
+                # We could test if e.orig is an instance of
+                # psycopg2.errors.LockNotAvailable/_mysql_exceptions.OperationalError, but that involves
+                # importing it. This doesn't
+                if db_err_code in ('55P03', 1205, 3572):
+                    self.log.debug("Critical section lock held by another Scheduler")
+                    Stats.incr('scheduler.critical_section_busy')
+                    session.rollback()
+                    return 0
+                raise
+
+            return num_queued_tis
+
+    def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control
+        if/when the next DAGRun should be created
+        """
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            dag_hash = self.dagbag.dags_hash.get(dag.dag_id, None)
+            dag.create_dagrun(
+                run_type=DagRunType.SCHEDULED,
+                execution_date=dag_model.next_dagrun,
+                start_date=timezone.utcnow(),
+                state=State.RUNNING,
+                external_trigger=False,
+                session=session,
+                dag_hash=dag_hash
+            )
+
+        self._update_dag_next_dagruns(dag_models, session)
+
+        # TODO[HA]: Should we do a session.flush() so we don't have to keep lots of state/object in
+        # memory for larger dags? or expunge_all()
+
+    def _update_dag_next_dagruns(self, dag_models: Iterable[DagModel], session: Session) -> None:
+        """
+        Bulk update the next_dagrun and next_dagrun_create_after for all the dags.
+
+        We batch the select queries to get info about all the dags at once
+        """
+        # Check max_active_runs, to see if we are _now_ at the limit for any of
+        # these dag? (we've just created a DagRun for them after all)
+        active_runs_of_dags = dict(session.query(DagRun.dag_id, func.count('*')).filter(
+            DagRun.dag_id.in_([o.dag_id for o in dag_models]),
+            DagRun.state == State.RUNNING,  # pylint: disable=comparison-with-callable
+            DagRun.external_trigger.is_(False),
+        ).group_by(DagRun.dag_id).all())
+
+        for dag_model in dag_models:
+            dag = self.dagbag.get_dag(dag_model.dag_id, session=session)
+            active_runs_of_dag = active_runs_of_dags.get(dag.dag_id, 0)
+            if dag.max_active_runs and active_runs_of_dag >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s is at (or above) max_active_runs (%d of %d), not creating any more runs",
+                    dag.dag_id, active_runs_of_dag, dag.max_active_runs
+                )
+                dag_model.next_dagrun_create_after = None
+            else:
+                dag_model.next_dagrun, dag_model.next_dagrun_create_after = \
+                    dag.next_dagrun_info(dag_model.next_dagrun)
+
+    def _schedule_dag_run(self, dag_run: DagRun, currently_active_runs: int, session: Session) -> int:
+        """
+        Make scheduling decisions about an individual dag run
+
+        ``currently_active_runs`` is passed in so that a batch query can be
+        used to ask this for all dag runs in the batch, to avoid an n+1 query.
+
+        :param dag_run: The DagRun to schedule
+        :param currently_active_runs: Number of currently active runs of this DAG
+        :return: Number of tasks scheduled
+        """
+        dag = dag_run.dag = self.dagbag.get_dag(dag_run.dag_id, session=session)
+
+        if not dag:
+            self.log.error(
+                "Couldn't find dag %s in DagBag/DB!", dag_run.dag_id
+            )
+            return 0
+
+        if (
+            dag_run.start_date and dag.dagrun_timeout and
+            dag_run.start_date < timezone.utcnow() - dag.dagrun_timeout
+        ):
+            dag_run.state = State.FAILED
+            dag_run.end_date = timezone.utcnow()
+            self.log.info("Run %s of %s has timed-out", dag_run.run_id, dag_run.dag_id)
+            session.flush()
+
+            # Work out if we should allow creating a new DagRun now?
+            self._update_dag_next_dagruns([session.query(DagModel).get(dag_run.dag_id)], session)
+
+            dag_run.callback = DagCallbackRequest(
+                full_filepath=dag.fileloc,
+                dag_id=dag.dag_id,
+                execution_date=dag_run.execution_date,
+                is_failure_callback=True,
+                msg='timed_out'
+            )
+
+            # Send SLA & DAG Success/Failure Callbacks to be executed
+            self._send_dag_callbacks_to_processor(dag_run)
+
+            return 0
+
+        if dag_run.execution_date > timezone.utcnow() and not dag.allow_future_exec_dates:
+            self.log.error(
+                "Execution date is in future: %s",
+                dag_run.execution_date
+            )
+            return 0
+
+        if dag.max_active_runs:
+            if currently_active_runs >= dag.max_active_runs:
+                self.log.info(
+                    "DAG %s already has %d active runs, not queuing any more tasks",
+                    dag.dag_id,
+                    currently_active_runs,
+                )
+                return 0
+
+        self._verify_integrity_if_dag_changed(dag_run=dag_run, session=session)
+        # TODO[HA]: Rename update_state -> schedule_dag_run, ?? something else?
+        schedulable_tis = dag_run.update_state(session=session, execute_callbacks=False)
+        # TODO[HA]: Don't return, update these from in update_state?
+
+        # Get list of TIs that do not need to executed, these are
+        # tasks using DummyOperator and without on_execute_callback / on_success_callback
+        dummy_tis = [
+            ti for ti in schedulable_tis
+            if
+            (
+                ti.task.task_type == "DummyOperator"
+                and not ti.task.on_execute_callback
+                and not ti.task.on_success_callback
+            )
+        ]
+
+        # This will do one query per dag run. We "could" build up a complex
+        # query to update all the TIs across all the execution dates and dag
+        # IDs in a single query, but it turns out that can be _very very slow_
+        # see #11147/commit ee90807ac for more details
+        count = session.query(TI).filter(
+            TI.dag_id == dag_run.dag_id,
+            TI.execution_date == dag_run.execution_date,
+            TI.task_id.in_(ti.task_id for ti in schedulable_tis if ti not in dummy_tis)
+        ).update({TI.state: State.SCHEDULED}, synchronize_session=False)
+
+        # Tasks using DummyOperator should not be executed, mark them as success
+        if dummy_tis:
+            session.query(TI).filter(
+                TI.dag_id == dag_run.dag_id,
+                TI.execution_date == dag_run.execution_date,
+                TI.task_id.in_(ti.task_id for ti in dummy_tis)
+            ).update({
+                TI.state: State.SUCCESS,
+                TI.start_date: timezone.utcnow(),
+                TI.end_date: timezone.utcnow(),
+                TI.duration: 0
+            }, synchronize_session=False)
+
+        return count
+
+    @provide_session
+    def _verify_integrity_if_dag_changed(self, dag_run: DagRun, session=None):
+        """Only run DagRun.verify integrity if Serialized DAG has changed since it is slow"""
+        latest_version = SerializedDagModel.get_latest_version_hash(dag_run.dag_id, session=session)
+        if dag_run.dag_hash == latest_version:
+            self.log.debug("DAG %s not changed structure, skipping dagrun.verify_integrity", dag_run.dag_id)
+            return
+
+        dag_run.dag_hash = latest_version
+
+        # Refresh the DAG
+        dag_run.dag = self.dagbag.get_dag(dag_id=dag_run.dag_id, session=session)
+
+        # Verify integrity also takes care of session.flush
+        dag_run.verify_integrity(session=session)
+
+    def _send_dag_callbacks_to_processor(self, dag_run: DagRun):
+        if not self.processor_agent:
+            raise ValueError("Processor agent is not started.")
+
+        dag = dag_run.get_dag()
+        self._manage_slas(dag)
+        if dag_run.callback:
+            self.processor_agent.send_callback_to_execute(dag_run.callback)
+
+    def _manage_slas(self, dag: DAG):

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/81129c252583e9dff54142eef1344749ea83c55b




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500591552



##########
File path: airflow/models/dag.py
##########
@@ -1824,10 +1960,34 @@ class DagModel(Base):
     # Tags for view filter
     tags = relationship('DagTag', cascade='all,delete-orphan', backref=backref('dag'))
 
+    concurrency = Column(Integer, nullable=False)
+
+    has_task_concurrency_limits = Column(Boolean, nullable=False)
+
+    # The execution_date of the next dag run
+    next_dagrun = Column(UtcDateTime)
+    # Earliest time at which this ``next_dagrun`` can be created
+    next_dagrun_create_after = Column(UtcDateTime)
+
     __table_args__ = (
         Index('idx_root_dag_id', root_dag_id, unique=False),
+        Index('idx_next_dagrun_create_after', next_dagrun_create_after, unique=False),
     )
 
+    NUM_DAGS_PER_DAGRUN_QUERY = conf.getint(
+        'scheduler',
+        'num_dags_needing_dagrun_per_scheduler_loop',
+        fallback=10
+    )

Review comment:
       This is mostly to avoid one scheduler getting all the work of creating the dag runs, (which can be an "expensive" step right now for large dags)
   
   Description I'm adding to config file is:
   
   ```
           This changes the number of dags that are locked by each scheduler when
           creating dag runs. One possible reason for setting this lower is if you
           have huge dags and are running multiple schedules, you won't want one
           scheduler to do all the work. (Default is 10)
   ```




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499532854



##########
File path: tests/jobs/test_backfill_job.py
##########
@@ -160,10 +160,11 @@ def test_trigger_controller_dag(self):
         )
         job.run()
 
-        task_instances_list = dag_file_processor._process_task_instances(
-            target_dag,
-            dag_runs=DagRun.find(dag_id='example_trigger_target_dag')
-        )
+        task_instances_list = []

Review comment:
       Er, no it doesn't look right. Will take a look.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ryw commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ryw commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-692908582


   We're working on a short doc that will provide an easy way to test all the components/PRs of AIP-15 together, and some preliminary benchmarks for performance improvement


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r499834162



##########
File path: airflow/models/dag.py
##########
@@ -1939,6 +2099,37 @@ def deactivate_deleted_dags(cls, alive_dag_filelocs: List[str], session=None):
             session.rollback()
             raise
 
+    @classmethod
+    def dags_needing_dagruns(cls, session: Session):
+        """
+        Return (and lock) a list of Dag objects that are due to create a new DagRun This will return a
+        resultset of rows  that is row-level-locked with a "SELECT ... FOR UPDATE" query, you should ensure
+        that any scheduling decisions are made in a single transaction -- as soon as the transaction is
+        committed it will be unlocked.
+        """
+        # TODO[HA]: Bake this query, it is run _A lot_
+        # TODO[HA]: Make this limit a tunable. We limit so that _one_ scheduler
+        # doesn't try to do all the creation of dag runs

Review comment:
       Good catch




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] ashb commented on pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
ashb commented on pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#issuecomment-693320542


   Process note: I intend to keep changes as fixups/separate commits even beyond rebasing/following master, hopefully to to make it easier to re-review this in future. (I.e. I will use `git rebase -i origin/master --no-autosquash`)


----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] kaxil commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r500616931



##########
File path: airflow/config_templates/config.yml
##########
@@ -1562,6 +1562,41 @@
       type: string
       example: ~
       default: "512"
+    - name: use_row_level_locking
+      description: |
+        Should the scheduler issue `SELECT ... FOR UPDATE` in relevant queries.
+        If this is set to False then you should not run more than a single
+        scheduler at once
+      version_added: 2.0.0
+      type: boolean
+      example: ~
+      default: "True"
+    - name: max_dagruns_to_create_per_loop
+      description: |
+        This changes the number of dags that are locked by each scheduler when
+        creating dag runs. One possible reason for setting this lower is if you
+        have huge dags and are running multiple schedules, you won't want one
+        scheduler to do all the work.
+
+        Default: 10
+      example: ~
+      version_added: 2.0.0
+      type: string
+      default: ~
+    - name: max_dagruns_per_loop_to_schedule
+      description: |
+        How many DagRuns should a scheduler exaimne (and lock) when scheduling
+        and queuing tasks. Increasing this limit will allow more throughput for
+        smaller DAGs but will likely slow down throughput for larger (>500
+        tasks for example.) DAGs. Setting this to high when using multiple

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/70fd17fc697a688545dd523ed5b91e74e7d81149

##########
File path: airflow/config_templates/config.yml
##########
@@ -1562,6 +1562,41 @@
       type: string
       example: ~
       default: "512"
+    - name: use_row_level_locking
+      description: |
+        Should the scheduler issue `SELECT ... FOR UPDATE` in relevant queries.
+        If this is set to False then you should not run more than a single
+        scheduler at once
+      version_added: 2.0.0
+      type: boolean
+      example: ~
+      default: "True"
+    - name: max_dagruns_to_create_per_loop
+      description: |
+        This changes the number of dags that are locked by each scheduler when
+        creating dag runs. One possible reason for setting this lower is if you
+        have huge dags and are running multiple schedules, you won't want one
+        scheduler to do all the work.
+
+        Default: 10
+      example: ~
+      version_added: 2.0.0
+      type: string
+      default: ~
+    - name: max_dagruns_per_loop_to_schedule
+      description: |
+        How many DagRuns should a scheduler exaimne (and lock) when scheduling

Review comment:
       Done in https://github.com/apache/airflow/pull/10956/commits/70fd17fc697a688545dd523ed5b91e74e7d81149




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [airflow] turbaszek commented on a change in pull request #10956: Officially support running more than one scheduler concurrently.

Posted by GitBox <gi...@apache.org>.
turbaszek commented on a change in pull request #10956:
URL: https://github.com/apache/airflow/pull/10956#discussion_r488899697



##########
File path: airflow/executors/base_executor.py
##########
@@ -69,16 +70,16 @@ def start(self):  # pragma: no cover
         """
 
     def queue_command(self,
-                      simple_task_instance: SimpleTaskInstance,

Review comment:
       Should we be able to remove `SimpleTaskInstance` totally from Airflow?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org