Skip to content

Record TaskInstanceHistory when a task fails from a non-running state - #67372

Merged
potiuk merged 3 commits into
apache:mainfrom
kalluripradeep:fix-ti-history-retry-metadata
Sep 21, 2026
Merged

potiuk merged 3 commits into
apache:mainfrom
kalluripradeep:fix-ti-history-retry-metadata

Conversation

@kalluripradeep

@kalluripradeep kalluripradeep commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

closes: #65366
closes: #67238

What happened?

When a task instance fails from a non-RUNNING state — e.g. the executor reports FAILED for a TI still QUEUED or SCHEDULED because the pod/worker was killed before the task started — the task is retried, but no TaskInstanceHistory row is written for the failed attempt. That attempt loses its hostname and dates, so the attempts tab in the UI has no entry and log retrieval fails with http://:8793 No host supplied.

Why?

fetch_handle_failure_context() only recorded history when the TI was running:

if ti.state == TaskInstanceState.RUNNING:
    ti.prepare_db_for_next_try(session)

handle_failure() has two callers (_process_executor_events and the heartbeat purge), and the reachable state set is {SCHEDULED, QUEUED, RUNNING, RESTARTING}. So a QUEUED or SCHEDULED failure skipped prepare_db_for_next_try() — and therefore TaskInstanceHistory.record_ti() — entirely.

What changed?

The guard now excludes only RESTARTING (task cleared via the UI/API, where prepare_db_for_next_try() already ran as part of the clear), so RUNNING, QUEUED and SCHEDULED all record their attempt:

if ti.state != TaskInstanceState.RESTARTING:
    ti.prepare_db_for_next_try(session)

Plus a parametrized regression test over QUEUED/SCHEDULED: after a FAILED executor event the TI must have a new UUID and a TaskInstanceHistory row preserving hostname and start_date.

This is a core-only change — nothing in the Kubernetes provider; KubernetesExecutor is just where the symptom is most visible.

@kalluripradeep
kalluripradeep force-pushed the fix-ti-history-retry-metadata branch 3 times, most recently from 7d3f9d0 to 190c0b6 Compare May 23, 2026 20:15
@potiuk potiuk added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label May 24, 2026
@Vamsi-klu

This comment was marked as spam.

@sagu2602

Copy link
Copy Markdown

Apache Airflow version: 3.2.0
So would this also solve logs tab missing attempts on UI when the task fails from QUEUED > FAILED??
For example: attempt-4 failed during QUEUED state

logs missing for task queued   failed

@kalluripradeep

Copy link
Copy Markdown
Contributor Author

@sagu2602 Yes — your scenario (attempt-4 fails while QUEUED, logs tab missing that attempt) is exactly what this PR fixes.

When a task fails from QUEUED state, the scheduler's executor-event path calls handle_failure(). Previously, TaskInstanceHistory was only recorded when ti.state == RUNNING, so a QUEUED failure silently dropped the history row → the attempts tab in the UI had no entry → logs showed nothing.

With this fix prepare_db_for_next_try() (which writes the TaskInstanceHistory row) is now called for QUEUED/SCHEDULED/DEFERRED states too, so attempt-4's hostname and dates will be recorded and the logs tab will show the attempt correctly.

@kalluripradeep

Copy link
Copy Markdown
Contributor Author

This still misses the scheduler executor-event path that triggers the KubernetesExecutor symptom. A failed executor event for a TI still in SCHEDULED/QUEUED enters the state-mismatch path, then calls ti.handle_failure(). But handle_failure() only records history when ti.state == RUNNING; otherwise it sets UP_FOR_RETRY without prepare_db_for_next_try(). Please add/fix the scheduler executor-event retry path and add a regression test where a non-running queued/scheduled TI receives a failed executor event and preserves TaskInstanceHistory.hostname/start_date.

Thanks for the detailed review — you're exactly right.

The root cause is in fetch_handle_failure_context() (line 1809 in taskinstance.py):

# Before
if ti.state == TaskInstanceState.RUNNING:
    ti.prepare_db_for_next_try(session)

When the executor sends a FAILED event for a QUEUED/SCHEDULED/DEFERRED TI, handle_failure() is called but ti.state != RUNNING, so prepare_db_for_next_try() — and therefore TaskInstanceHistory.record_ti() — was never invoked. History lost, hostname gone.

Fixed by changing the guard to exclude only RESTARTING (which already had prepare_db_for_next_try called during the clear operation):

# After
if ti.state != TaskInstanceState.RESTARTING:
    # Covers RUNNING (normal exception), QUEUED/SCHEDULED/DEFERRED (external kill)
    ti.prepare_db_for_next_try(session)

Added a parametrized regression test test_process_executor_events_queued_ti_retry_preserves_history covering both QUEUED and SCHEDULED states — verifies that after a FAILED executor event: TI gets a new UUID (confirming prepare_db_for_next_try ran), a TaskInstanceHistory row exists, and hostname/start_date are preserved.

@dabla dabla left a comment

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.

Nice fix but would be more confident if @uranusjr could also verify.

# Conflicts:
#	airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py
#	airflow-core/src/airflow/models/taskinstancehistory.py

@shahar1 shahar1 left a comment

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.

Could you please think of another title for this PR?
The issue might be surfaced in KubernetesExecutor, but the fix is not in the Kubernetes provider - which is rather confusing.

@kalluripradeep

Copy link
Copy Markdown
Contributor Author

Could you please think of another title for this PR? The issue might be surfaced in KubernetesExecutor, but the fix is not in the Kubernetes provider - which is rather confusing.

@shahar1 Good point — retitled to "Record TaskInstanceHistory when a task fails from a non-running state".

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving — the condition change is correct and the regression test is a real one. Three non-blocking cleanups inline that I'd like you to take a look at before this goes in; none of them changes behaviour.

The parts I went looking for problems in and didn't find any:

  • Excluding RESTARTING is not optional, and you got it right. is_eligible_to_retry() returns True unconditionally for RESTARTING (taskinstance.py:2000-2003), so a cleared task does reach this else branch — a plain != RUNNING would have recorded its history twice.
  • No retry is silently consumed. prepare_db_for_next_try() records history, clears TaskReschedule rows and re-issues the UUID, but never touches try_number — that increment lives in dagrun.py:2292. Extending the call to QUEUED/SCHEDULED doesn't cost an attempt.
  • A double call would be harmless anyway. TaskInstanceHistory.record_ti() early-returns when a row already exists for the same try_number (taskinstancehistory.py:196-206).
  • Newsfragment present and correctly typed, and the reachable-state set across both handle_failure() callers is exactly {SCHEDULED, QUEUED, RUNNING} — precisely what the new condition selects.

Smaller observations

Two of the three inline comments are the same point: the test additions in test_task_instances.py and in test_adopt_or_reset_resettable_tasks cover code that was already on main before this PR and pass without your change. The third is a comment listing DEFERRED as a reachable state when it isn't.

One more, with no line to anchor it to: the PR description describes two production changes that aren't in the diff — the record_ti FAILED/end_date forcing (taskinstancehistory.py:207-213) and the Execution API end_date / rendered_map_index snapshot (task_instances.py:683-688). Both were already on main; the actual change here is the five-line condition. Worth trimming the description so the next reader isn't hunting for code that isn't there.

Finally, something to consider rather than change: != RESTARTING is a deny-list against an open enum. It's correct for today's two callers, but a future caller arriving in UP_FOR_RESCHEDULE or with state=None would silently get a history row and a fresh UUID. An explicit in (RUNNING, QUEUED, SCHEDULED) would keep the invariant local and fail safe. Not asking you to change it — just flagging the trade-off.


This review was drafted by an AI-assisted tool and confirmed by an Airflow maintainer. The maintainer approving this PR has read the findings and signed off. If something feels off, please reply on the PR and a maintainer will follow up.

More on how Airflow handles maintainer review: contributing-docs/05_pull_requests.rst.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

@kalluripradeep

Copy link
Copy Markdown
Contributor Author

@potiuk Thanks — all three applied.

  1. Dropped DEFERRED from the comment.
  2. Reverted the test_task_instances.py hunk entirely, including the
    hostname/start_date setup that only fed it. That file is now untouched by
    this PR.
  3. Reverted the test_adopt_or_reset_resettable_tasks additions the same way.

Also trimmed the PR description — it described the record_ti FAILED forcing
and the Execution API snapshot, both of which were already on main. The diff
is now the newsfragment, the five-line condition, and the regression test.

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

Labels

area:API Airflow's REST/HTTP API area:scheduler area:task-sdk ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green.

Projects

None yet

6 participants