Repository navigation
Conversation
|
Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
|
| def _handle_task_failure(cls, ti: TI, *, error: str, session: Session) -> None: | ||
| task_instance_key = ti.key | ||
| # begin_nested flushes pending batch changes before opening the savepoint. | ||
| savepoint = session.begin_nested() | ||
| try: | ||
| with savepoint: | ||
| ti.handle_failure(error=error, session=session) | ||
| except Exception as exc: | ||
| if not session.is_active or (isinstance(exc, DBAPIError) and exc.connection_invalidated): | ||
| raise | ||
| cls.logger().exception( | ||
| "Could not handle task instance failure", task_instance_key=task_instance_key | ||
| ) | ||
| ti.set_state(TaskInstanceState.FAILED, session=session) |
There was a problem hiding this comment.
Right now it only wraps the handle_failure() call. But when the scheduler decides a TI has failed, handle_failure() is just the last step. Before it, in the same branch, we also load the task and build and send the TaskCallbackRequest / EmailRequest (_resolve_ti_callback_bundle_info, task_instance_to_runtime, DRDataModel.model_validate, ...). _purge_task_instances_without_heartbeats has a similar block. If anything in there raises for one TI, we're back to the same crash this PR is trying to prevent.
What do you think about moving the savepoint up so it covers that whole "fail this TI" block? For example, turn the helper into a context manager, keeping the guards you already have:
@classmethod
@contextmanager
def _isolate_failure_handling(cls, ti: TI, *, session: Session) -> Iterator[None]:
task_instance_key = ti.key
try:
with session.begin_nested():
yield
except Exception as exc:
if not session.is_active or (isinstance(exc, DBAPIError) and exc.connection_invalidated):
raise
cls.logger().exception("Could not handle task instance failure", task_instance_key=task_instance_key)
ti.set_state(TaskInstanceState.FAILED, session=session)and use it around the existing code in process_executor_events:
if ti_queued and not ti_requeued:
...
session.add(Log(event="state mismatch", ...)) # outside, so the audit entry survives the fallback
with cls._isolate_failure_handling(ti, session=session):
# load task, send callback / email requests (unchanged)
ti.handle_failure(error=msg, session=session)In the heartbeat purge, the same with would go from _resolve_ti_callback_bundle_info(ti) down to the handle_failure() call, leaving the heartbeat timeout Log outside.
This would also cover the callback/retry mismatch in the next comment, since the queued requests would be rolled back together with the failed handling.
| def _handle_task_failure(cls, ti: TI, *, error: str, session: Session) -> None: | ||
| task_instance_key = ti.key | ||
| # begin_nested flushes pending batch changes before opening the savepoint. | ||
| savepoint = session.begin_nested() | ||
| try: | ||
| with savepoint: | ||
| ti.handle_failure(error=error, session=session) | ||
| except Exception as exc: | ||
| if not session.is_active or (isinstance(exc, DBAPIError) and exc.connection_invalidated): | ||
| raise | ||
| cls.logger().exception( | ||
| "Could not handle task instance failure", task_instance_key=task_instance_key | ||
| ) | ||
| ti.set_state(TaskInstanceState.FAILED, session=session) |
There was a problem hiding this comment.
In the executor-event path the failure/retry callback and the email request are sent before this helper runs (L1826, L1858). DatabaseCallbackSink.send() only does session.add(), and begin_nested() flushes that before the savepoint opens, so rolling back the savepoint does not remove them.
For a task that still has retries left, the queued callback/email says UP_FOR_RETRY (task_callback_type is computed from ti.is_eligible_to_retry() at L1813), but this fallback then puts the TI into a terminal FAILED and it never retries. So the user's on_retry_callback fires for a retry that never happens.
The test only uses max_tries = 0, so it does not cover this. Either moving the callback/email requests inside the same savepoint, or choosing a fallback that respects retries, would keep them consistent. Whichever state is chosen, it would help to state in the PR description that the fallback skips retries, fail_fast and listeners, since the issue left the fallback state as an open question.
| ti.updated_at = timezone.utcnow() | ||
| session.merge(ti) | ||
| session.flush() | ||
| session.commit() |
There was a problem hiding this comment.
Before this, the first handle_failure() in process_executor_events committed the whole scheduler transaction mid-loop. That also released the with_row_locks(..., skip_locked=True) locks on the rest of the batch, so another HA scheduler could pick those TIs up while this one was still iterating. After this change, failures are committed once per batch with the rest of the loop's work, and an exception raised outside the savepoint later in the batch now rolls back the earlier TIs too, where previously they had already been committed.
Both seem fine to me (and the first is a fix), but since the behaviour changes, it would help reviewers and anyone bisecting later if this were described, or kept as a separate commit.
One task instance can leave the scheduler unable to process any further work when its failure handler raises.
8faf2bb to
1089650
Compare
|
@ChickenBenny resolved the conflicts and widened the savepoint so failed task handling also rolls back queued callbacks and emails, audit logs stay intact. ptal when you get a chance |
If task failure handling raises, the scheduler can exit before processing the rest of the batch and hit the same task again after a restart.
Put task loading, callback context construction, callback and email queueing, and failure handling inside the same per-task savepoint. Keep the audit log outside it. On a recoverable error, roll back that task's changes and mark it failed so the remaining tasks can proceed.
Normal failures still follow the configured retry policy. The exceptional fallback is terminal: it skips retries, fail_fast propagation, and failure listeners rather than re-entering the failed handler. Unusable sessions and invalidated connections still propagate to the outer transaction handler.
TaskInstance.save_to_dbnow flushes without committing. The caller owns the batch transaction and its HA locks until commit; a later outer rollback also rolls back earlier task updates in that batch.Validation on Python 3.12:
Six new retry notification cases fail on the previous implementation. They cover callback context, email queueing, and failure handler errors in both executor and heartbeat paths. Full Breeze core and docs checks remain for CI.
For this review update, measured 24 executor events per batch against the rebased previous PR implementation, with one warmup and three alternating measured runs per version on SQLite:
These are medians from a shared host, not a throughput claim. Expanding the existing savepoint adds no SQL statements.
closes: #76529
related: #76191
Was generative AI tooling used to co-author this PR?
Generated-by: OpenAI Codex (GPT-6) following the guidelines