Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,17 @@ def ti_update_state(
)

if previous_state != TaskInstanceState.RUNNING:
# In HA, it's possible to receive a "late" finish/state update after another
# component already moved the TI to a terminal state. Treat this as an idempotent no-op to avoid
# crashing the process.
Comment on lines +387 to +389
Copy link
Member

Choose a reason for hiding this comment

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

Wait -- how can this happen? If another component already moved to terminal state -- it means task was running in that other component/worker -- not the one that triggered this.

Copy link
Member

Choose a reason for hiding this comment

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

2 workers shouldn't be running the same task!

Copy link
Member

@potiuk potiuk Dec 23, 2025

Choose a reason for hiding this comment

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

I think this might happen in some edge cases of CeleryExecutor race conditions when celery thinks that task has not completed and cancels it (but it finishes between it gets cancelled) and sends the task and it gets picked by another worker.

Possibly there are similar edge cases in K8S executor. I think It would be great to describe the semantics of task execution for both - > at most once (which we don't have), at least once (which I think we have), exactly-once (which I think is not really achievable easily - without adding a lot of complexity).

Choose a reason for hiding this comment

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

2 workers shouldn't be running the same task!

That's true, but it's happening in the K-Executor :/ #57618 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm going to verify this more but here's what I thought was going on:

Scheduler A tried to start X but the scheduler was marked failed. Scheduler B picked up the task(couldn't adopt) after resetting it and start X in another pod. At this point we now have two pods running. So I think one of the pods received an update state before the other.

Copy link
Contributor

Choose a reason for hiding this comment

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

I have experienced the same state update issues with the CeleryExecutor, as well. It doesn't appear to be isolated to the k8s executor.

Copy link
Member

Choose a reason for hiding this comment

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

@pdellarciprete That's a bug somewhere that needs fixing but the current fix here -- which this comment thread is for -- is too late. What needs to be fixed is workers not able to even run duplicate task -- not when task has run on both workers and both are trying to update it state.

This endpoint in this file is for the same.

Copy link
Contributor Author

@ephraimbuddy ephraimbuddy Jan 5, 2026

Choose a reason for hiding this comment

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

So it looks like the earlier PR fixed this issue and I wasn't testing on the right branch when I raised this. @pdellarciprete , can you confirm you are no longer seeing this issue after applying the previous fix(#59639)

Oh, disregard this. I was testing with 1 scheduler

if previous_state in set(TerminalTIState):
Copy link
Member

Choose a reason for hiding this comment

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

Is the set() cast needed?

requested_state = getattr(ti_patch_payload.state, "value", ti_patch_payload.state)
log.info(
"Ignoring state update for already terminal task instance",
previous_state=previous_state,
requested_state=requested_state,
)
return
log.warning(
"Cannot update Task Instance in invalid state",
previous_state=previous_state,
Expand Down
8 changes: 8 additions & 0 deletions airflow-core/src/airflow/jobs/scheduler_job_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2584,8 +2584,16 @@ def adopt_or_reset_orphaned_tasks(self, session: Session = NEW_SESSION) -> int:
reset_tis_message = []
for ti in to_reset:
reset_tis_message.append(repr(ti))
# If we reset a TI, it will be eligible to be scheduled again.
# This can cause the scheduler to increase the try_number on the TI.
# Record the current try to TaskInstanceHistory first so users have an audit trail for
# the attempt that was abandoned.
ti.prepare_db_for_next_try(session=session)

ti.state = None
ti.queued_by_job_id = None
ti.external_executor_id = None
ti.clear_next_method_args()

for ti in set(tis_to_adopt_or_reset) - set(to_reset):
ti.queued_by_job_id = self.job.id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1353,8 +1353,8 @@ def test_ti_update_state_to_failed_table_check(self, client, session, create_tas
assert ti.next_kwargs is None
assert ti.duration == 3600.00

def test_ti_update_state_not_running(self, client, session, create_task_instance):
"""Test that a 409 error is returned when attempting to update a TI that is not in RUNNING state."""
def test_ti_update_state_not_running_terminal_is_idempotent(self, client, session, create_task_instance):
"""Test that updating a terminal TI is treated as an idempotent no-op."""
ti = create_task_instance(
task_id="test_ti_update_state_not_running",
state=State.SUCCESS,
Expand All @@ -1368,17 +1368,40 @@ def test_ti_update_state_not_running(self, client, session, create_task_instance
"end_date": DEFAULT_END_DATE.isoformat(),
}

response = client.patch(f"/execution/task-instances/{ti.id}/state", json=payload)
assert response.status_code == 204
assert response.text == ""

# Verify the task instance state hasn't changed
session.refresh(ti)
assert ti.state == State.SUCCESS

def test_ti_update_state_not_running_non_terminal(self, client, session, create_task_instance):
"""Test that a 409 error is returned when attempting to update a TI that is not in RUNNING state."""
ti = create_task_instance(
task_id="test_ti_update_state_not_running_non_terminal",
state=State.QUEUED,
session=session,
start_date=DEFAULT_START_DATE,
)
session.commit()

payload = {
"state": "failed",
"end_date": DEFAULT_END_DATE.isoformat(),
}

response = client.patch(f"/execution/task-instances/{ti.id}/state", json=payload)
assert response.status_code == 409
assert response.json()["detail"] == {
"reason": "invalid_state",
"message": "TI was not in the running state so it cannot be updated",
"previous_state": State.SUCCESS,
"previous_state": State.QUEUED,
}

# Verify the task instance state hasn't changed
session.refresh(ti)
assert ti.state == State.SUCCESS
assert ti.state == State.QUEUED

def test_ti_update_state_to_failed_without_fail_fast(self, client, session, dag_maker):
"""Test that SerializedDAG is NOT loaded when fail_fast=False (default)."""
Expand Down
20 changes: 20 additions & 0 deletions airflow-core/tests/unit/jobs/test_scheduler_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -4060,6 +4060,8 @@ def test_adopt_or_reset_orphaned_tasks_nothing(self):
list(sorted(State.adoptable_states)),
)
def test_adopt_or_reset_resettable_tasks(self, dag_maker, adoptable_state, session):
from airflow.models.taskinstancehistory import TaskInstanceHistory

dag_id = "test_adopt_or_reset_adoptable_tasks_" + adoptable_state.name
with dag_maker(dag_id=dag_id, schedule="@daily"):
task_id = dag_id + "_task"
Expand All @@ -4074,13 +4076,31 @@ def test_adopt_or_reset_resettable_tasks(self, dag_maker, adoptable_state, sessi
ti = dr1.get_task_instances(session=session)[0]
ti.state = adoptable_state
ti.queued_by_job_id = old_job.id
old_ti_id = ti.id
old_try_number = ti.try_number
session.merge(ti)
session.merge(dr1)
session.commit()

num_reset_tis = self.job_runner.adopt_or_reset_orphaned_tasks(session=session)
assert num_reset_tis == 1

ti.refresh_from_db(session=session)
assert ti.id != old_ti_id
assert (
session.scalar(
select(TaskInstanceHistory).where(
TaskInstanceHistory.dag_id == ti.dag_id,
TaskInstanceHistory.task_id == ti.task_id,
TaskInstanceHistory.run_id == ti.run_id,
TaskInstanceHistory.map_index == ti.map_index,
TaskInstanceHistory.try_number == old_try_number,
TaskInstanceHistory.task_instance_id == old_ti_id,
)
)
is not None
)

def test_adopt_or_reset_orphaned_tasks_external_triggered_dag(self, dag_maker, session):
dag_id = "test_reset_orphaned_tasks_external_triggered_dag"
with dag_maker(dag_id=dag_id, schedule="@daily"):
Expand Down
Loading