dabla commented on code in PR #77546:
URL: https://github.com/apache/airflow/pull/77546#discussion_r4686457426
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1338,17 +1352,39 @@ def _get_sentry_integration(executor: BaseExecutor) ->
str:
return ""
return sentry_integration
- log_contexts = prepare_task_log_contexts(
- [
- ti
- for ti in task_instances
- if ti.dag_version_id and ti.dag_run.state not in
State.finished_dr_states
- ],
- session=session,
- dag_bag=self.scheduler_dag_bag,
- filename_template=conf.get("logging", "log_filename_template"),
- )
+ log_tis = [
+ ti
+ for ti in task_instances
+ if ti.dag_version_id and ti.dag_run.state not in
State.finished_dr_states
+ ]
+ while True:
+ try:
+ log_contexts = prepare_task_log_contexts(
+ log_tis,
+ session=session,
+ dag_bag=self.scheduler_dag_bag,
+ filename_template=conf.get("logging",
"log_filename_template"),
+ )
+ break
+ except KeyError:
Review Comment:
**[warning]** The scheduler learns that a task instance was deleted by
catching `KeyError` from `prepare_task_log_contexts`, then queries to find out
whether that is what the `KeyError` meant.
`prepare_task_log_contexts` is ninety lines that index several dictionaries
(`runs[...]`, `regions[...]`, and whatever `region_log_position` does with
them, [`task_log_address.py`
L236-L255](https://github.com/apache/airflow/blob/7ca42fd6d169ae88c96be3e062ae77e83a5e97ef/airflow-core/src/airflow/utils/log/task_log_address.py#L236-L255)).
Any of them raising for another reason while one task instance of the batch
happens to be gone is read as "deleted", the batch is rebuilt, and the real
error only shows on the next pass, if it repeats. The loop and the extra
`SELECT` exist to work back from the exception to its cause.
The function that walks the regions is the one that knows which region is
missing. If it left out the task instances whose region it could not load, or
raised an exception of its own that names them, the caller would drop exactly
those and build the rest in one pass, with no `while True` and no inference
from a built-in exception ("Errors should never pass silently", [PEP
20](https://peps.python.org/pep-0020/)). The test
`test_log_address_failure_not_caused_by_a_deletion_is_raised` would then not
need to exist.
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1204,16 +1204,42 @@ def _build_schedulable_tis_query(
# transient (via make_transient) before ExecuteTask.make() reads
# ti.dag_run.created_dag_version.version_data to ship the bundle
manifest matching
# the run's pinned bundle_version. Lazy loads on transient objects
silently return
- # None instead of raising DetachedInstanceError. Scope the SELECT
to version_data
- # (the PK is auto-included) so we read two columns rather than the
full row.
+ # None instead of raising DetachedInstanceError. Scope the SELECT
to version_data and
+ # bundle_version, the columns ExecuteTask.make() reads (the PK is
auto-included), to
+ # avoid a lazy load after the commit, which fails once the Dag is
deleted.
.options(
joinedload(TI.dag_run)
.selectinload(DagRun.created_dag_version)
- .load_only(DagVersion.version_data)
+ .load_only(DagVersion.version_data, DagVersion.bundle_version)
)
.limit(max_tis)
)
+ def _build_pre_assigning_executor_filter(self) -> ColumnElement[bool] |
bool:
Review Comment:
**[warning]** `_build_pre_assigning_executor_filter` returns `True`, `False`
or a SQL condition, and both callers have to tell the three apart with `is
True` and `is not False`.
A caller that forgets and writes `if pre_assigning:` gets SQLAlchemy's
"Boolean value of this clause is not defined" for the mixed case only, which is
the case with the least test coverage. Two questions are being answered by one
value: "does any executor pre-assign?" (a plain `bool`, which is what the
`RETURNING` read-back and the two early exits need) and "which rows?" (a
condition). Returning the condition always, with `sqlalchemy.true()` when every
executor opts in, and asking the first question separately
(`any(e.pre_assigns_external_executor_id for e in self.executors)`) keeps one
return type and lets both callers build the same `case(...)` without branching.
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1411,25 +1452,162 @@ def _critical_section_enqueue_task_instances(self,
session: Session) -> int:
max_tis = min(self.job.max_tis_per_query, self._parallelism -
num_occupied_slots)
if max_tis <= 0:
self.log.debug("max_tis query size is less than or equal to zero.
No query will be performed!")
- return 0
+ return []
pools, max_tis, starved_pools = self._acquire_pool_capacity(max_tis,
session=session)
if max_tis == 0:
- return 0
- queued_tis = self._select_task_instances_to_queue(max_tis, pools,
starved_pools, session=session)
+ return []
+ return self._select_task_instances_to_queue(max_tis, pools,
starved_pools, session=session)
+ def _enqueue_workloads(self, queued_tis: list[TI], *, session: Session) ->
int:
+ """
+ Build the workloads of TaskInstances already committed as QUEUED and
enqueue them in their executors.
+
+ :return: How many workloads were enqueued.
+ """
+ # Committing the QUEUED state released the row locks the selection
took, so another transaction may
+ # have changed or deleted some of these task instances since. Building
the workloads does not lock
+ # them again: it only builds workloads for the ones still queued by
this scheduler.
+ still_queued_ids = set(
+ session.scalars(
+ select(TI.id).where(
+ TI.id.in_([ti.id for ti in queued_tis]),
+ TI.state == TaskInstanceState.QUEUED,
+ TI.queued_by_job_id == self.job.id,
+ )
+ )
+ )
+ if len(still_queued_ids) < len(queued_tis):
+ skipped = [ti for ti in queued_tis if ti.id not in
still_queued_ids]
+ self.log.info(
+ "Not enqueuing %s of %s task instances changed or deleted
after they were queued",
+ len(skipped),
+ len(queued_tis),
+ )
+ self.log.debug("Task instances changed or deleted after they were
queued: %s", skipped)
+ queued_tis = [ti for ti in queued_tis if ti.id in still_queued_ids]
# Sort queued TIs to their respective executor
executor_to_queued_tis = self._executor_to_workloads(queued_tis,
session)
+ num_enqueued = 0
for executor, queued_tis_per_executor in
executor_to_queued_tis.items():
self.log.info(
"Trying to enqueue tasks: %s for executor: %s",
queued_tis_per_executor,
executor,
)
-
self._enqueue_task_instances_with_queued_state(queued_tis_per_executor,
executor, session=session)
+ num_enqueued += self._enqueue_task_instances_with_queued_state(
+ queued_tis_per_executor, executor, session=session
+ )
+ return num_enqueued
- return len(queued_tis)
+ def _enqueue_workloads_or_reset(
Review Comment:
**[warning]** Handing a committed batch to the executors, and undoing it
when that fails, is a unit of its own that lands as five more methods on
`SchedulerJobRunner`.
`_enqueue_workloads`, `_enqueue_workloads_or_reset`, `_reset_batch`,
`_discard_unsent_workloads` and `_reset_task_instances_to_scheduled` only call
each other, and `queued_tis`, `guard` and `session` travel through them
together. That is the case for [Extract
Class](https://refactoring.com/catalog/extractClass.html): a small object built
with the batch, the guard, the session and the executors, with one public
method that enqueues or resets. The file is already past 5,000 lines, and this
is the part of the change whose failure paths are hardest to follow in place;
on its own it could be read and tested without a `SchedulerJobRunner` around
it. I would also be fine with this as a follow-up if you prefer to keep this PR
to the behaviour 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.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]