Skip to content

Keep the scheduler running when task failure handling raises - #76544

Open
its-amann wants to merge 2 commits into
apache:mainfrom
its-amann:fix/scheduler-failure-isolation-76529
Open

its-amann wants to merge 2 commits into
apache:mainfrom
its-amann:fix/scheduler-failure-isolation-76529

Conversation

@its-amann

@its-amann its-amann commented Nov 5, 2026 •

Copy link
Copy Markdown

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_db now 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:

  • Scheduler suite: 679 passed, 20 skipped on SQLite.
  • Task instance and clear-task suites: 540 passed, 6 skipped on SQLite.
  • PostgreSQL 16: 21 focused cases passed, including retry notification rollback and heartbeat fail_fast behavior.
  • Applicable regular and manual prek checks passed, including airflow-core mypy.

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:

Batch Previous PR Updated SQL statements
Failure handling 232.7 ms 229.6 ms 390 in both
Already finished tasks 9.25 ms 8.96 ms 5 in both

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?
  • Yes, OpenAI Codex (GPT-6)

Generated-by: OpenAI Codex (GPT-6) following the guidelines

@boring-cyborg

boring-cyborg Bot commented Nov 5, 2026

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
Here are some useful points:

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

Comment on lines +1503 to +1516
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)

@ChickenBenny ChickenBenny Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +1503 to +1516
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@its-amann
its-amann force-pushed the fix/scheduler-failure-isolation-76529 branch from 8faf2bb to 1089650 Compare November 28, 2026 16:03
@its-amann

Copy link
Copy Markdown
Author

@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

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Scheduler exits when handle_failure raises for a single task instance

2 participants