Skip to content

Fix task cancellation during graceful worker shutdown - #8343

Open
YasenT wants to merge 1 commit into
pulp:mainfrom
YasenT:fix-cancel-during-graceful-shutdown
Open

YasenT wants to merge 1 commit into
pulp:mainfrom
YasenT:fix-cancel-during-graceful-shutdown

Conversation

@YasenT

@YasenT YasenT commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Replaces #8304, which was closed by mistake and could not be reopened.

Problem

If a task is canceled while its worker is shutting down gracefully, the task never aborts and the worker deadlocks:

  1. SIGTERM/SIGHUP → _signal_handler sets task_grace_timeout = None ("wait forever" for the in-flight task).
  2. The task is canceled → supervise_task sets cancel_state, but the kill branch was gated on the same field:
    if self.task_grace_timeout is None or self.task_grace_timeout > timezone.now():
        _logger.info("Wait for canceled task to abort.")   # forever
    else:
        os.kill(task_process.pid, signal.SIGUSR1)          # never reached
  3. SIGUSR1 is never sent, so the task stays in canceling. The worker can't exit and keeps heartbeating, so dead-worker cleanup never reclaims its locks. Every task queued on the task's exclusive resources is blocked indefinitely.

We hit this in production: a straggler pod from a rollout wedged on a canceled pulp_python upload_group task, with 120+ tasks queued behind its repository lock. It logged Worker shutdown requested, waiting for task … and Wait for canceled task to abort. indefinitely until the pod was force-deleted. Nothing about this is specific to the task type; any task canceled during a graceful shutdown is affected.

Fix

Applied identically to PulpcoreWorker and RedisWorker:

  • Track the kill deadline for a canceled (or shutdown-aborted) task in a separate cancel_kill_deadline, reset per supervised task. An explicit cancellation now sends SIGUSR1 immediately, whatever the shutdown grace setting. The cancel path also stops overwriting task_grace_timeout (previously it pushed the shutdown grace timer forward by TASK_KILL_INTERVAL on every kill).
  • Once a task is being aborted, the shutdown branch no longer runs, so a user cancellation stays canceled and isn't rewritten to failed ("Aborted during worker shutdown") when the grace period expires.

Escalation is unchanged: the task's child_signal_handler resets SIGUSR1 to SIG_DFL on the first signal, so a task that doesn't exit is terminated by the next SIGUSR1 one TASK_KILL_INTERVAL later.

Tests

pulpcore/tests/unit/tasking/test_cancel_during_graceful_shutdown.py drives supervise_task for both worker types with a fake task process (no DB or Redis needed):

  • cancel during graceful shutdown → SIGUSR1 sent, task ends canceled (fails on main with the deadlock guard, passes with this change)
  • cancel during normal operation → unchanged
  • graceful shutdown without a cancel → still waits for the task to finish, no kill

🤖 Generated with Claude Code

@dkliban dkliban 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.

The fix looks correct, but several of the new code paths aren't actually executed by the tests — they pass whether or not those lines are present. Both "graceful" cases use task_grace_timeout = None, and the FakeProcess exits on the first SIGUSR1, so the moderately-graceful branch and the escalation logic never run. Could we add cases that exercise them? (Each of the cases below should be mirrored for both PulpcoreWorker and RedisWorker — a gap in one is a gap in the other.)

1. The and not cancel_state guard (keeps a cancel as CANCELED, not FAILED)

Deleting and not cancel_state from both workers currently leaves every test green — the guard only matters when task_grace_timeout is a past time, which no test sets. Suggested case:

def test_pulpcore_worker_cancel_during_moderate_shutdown_stays_canceled(monkeypatch, in_tmp_dir):
    worker = _pulpcore_worker(graceful_shutdown=True)
    # moderately graceful: grace already expired, so the shutdown branch
    # would abort the task to FAILED if the cancel weren't guarding it
    worker.task_grace_timeout = worker_module.timezone.now() - timedelta(seconds=1)
    harness = Harness(
        monkeypatch, worker_module,
        on_first_select=lambda: setattr(worker, "cancel_task", True),
    )
    task = _make_task()

    worker.supervise_task(task)

    assert harness.kills == [signal.SIGUSR1]
    worker.cancel_abandoned_task.assert_called_once_with(task, TASK_STATES.CANCELED, None)

(+ the RedisWorker equivalent, asserting task.set_canceled.assert_called_once_with(final_state=TASK_STATES.CANCELED, reason=None).)

2. The shutdown-abort branch itself (cancel_state = FAILED)

The else branch that sets FAILED / "Aborted during worker shutdown." — and the new self.cancel_kill_deadline = now() line inside it — never runs, because both shutdown tests use task_grace_timeout = None. A case with an expired grace period and no cancel would cover it:

def test_pulpcore_worker_moderate_shutdown_aborts_task(monkeypatch, in_tmp_dir):
    worker = _pulpcore_worker(graceful_shutdown=True)
    worker.task_grace_timeout = worker_module.timezone.now() - timedelta(seconds=1)
    harness = Harness(monkeypatch, worker_module)
    task = _make_task()

    worker.supervise_task(task)

    assert harness.kills == [signal.SIGUSR1]
    worker.cancel_abandoned_task.assert_called_once_with(
        task, TASK_STATES.FAILED, "Aborted during worker shutdown."
    )

3. Escalation — the second SIGUSR1 for a task that ignores the first

fake_kill finishes the process on the first SIGUSR1 and every test asserts exactly one kill, so the cancel_kill_deadline = now() + TASK_KILL_INTERVAL wait-then-re-kill cycle (the actual deadline mechanism) is never exercised. If FakeProcess could be told to survive the first signal — e.g. a kills_needed count so it only finishes on the Nth SIGUSR1 — a test could assert harness.kills == [signal.SIGUSR1, signal.SIGUSR1] and that the worker waited between them. This is the part that guarantees a stubborn task actually dies.

4. (Optional) Pin that cancel no longer mutates task_grace_timeout

Re-adding self.task_grace_timeout = ... to the cancel branch would pass all current tests. A one-line assertion after a cancel that worker.task_grace_timeout is unchanged would lock that in.


Worth sanity-checking each new case by reverting the corresponding production line (e.g. git stash the guard or the FAILED assignment) and confirming the test fails — otherwise it's easy to add a test that passes incidentally rather than because of the behavior it pins.

A graceful shutdown (SIGTERM/SIGHUP) sets task_grace_timeout to None so the
worker waits indefinitely for the running task. The cancellation path reused
task_grace_timeout as its kill deadline, so canceling that task only logged
"Wait for canceled task to abort." forever and never sent SIGUSR1. The task
stayed in "canceling", the worker could never exit, and it kept heartbeating
while holding the task's exclusive resource locks, blocking every task queued
on them.

Track the kill deadline for a canceled (or shutdown-aborted) task in a separate
cancel_kill_deadline, reset per task, so an explicit cancellation takes effect
regardless of the shutdown grace period. This also stops the cancel path from
mutating task_grace_timeout. Once a task is being aborted, the shutdown branch
no longer overrides its state, so a user cancellation stays CANCELED instead of
becoming FAILED.

Applied to both PulpcoreWorker and RedisWorker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@YasenT
YasenT force-pushed the fix-cancel-during-graceful-shutdown branch from 11ebc3b to b0a4147 Compare November 24, 2026 12:42
@YasenT

YasenT commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @dkliban! All four points are addressed in the amended commit, each mirrored for PulpcoreWorker and RedisWorker:

  1. and not cancel_state guard: test_*_cancel_during_moderate_shutdown_stays_canceled sets an already-expired task_grace_timeout, cancels the task, and asserts it ends CANCELED rather than FAILED.
  2. Shutdown-abort branch: test_*_moderate_shutdown_aborts_task covers an expired grace period with no cancel and asserts a single SIGUSR1 and FAILED / "Aborted during worker shutdown.".
  3. Escalation: Harness now takes kills_needed, so the fake task only exits on the Nth SIGUSR1, and it patches the module's timezone with a fake clock that advances on every select. test_*_cancel_escalates_if_task_ignores_kill (graceful-shutdown and running) asserts kills == [SIGUSR1, SIGUSR1] and that the second kill came at least TASK_KILL_INTERVAL after the first.
  4. task_grace_timeout not mutated: the cancel and escalation tests now assert it is unchanged after the cancel.

As you suggested, I reverted each production line in both workers and confirmed the corresponding tests fail:

Reverted Failing tests
and not cancel_state both *_stays_canceled
cancel_state = TASK_STATES.FAILED in the shutdown branch both *_moderate_shutdown_aborts_task (deadlock guard trips)
self.cancel_kill_deadline = timezone.now() in the shutdown branch both *_moderate_shutdown_aborts_task
cancel_kill_deadline = now() + TASK_KILL_INTERVAL → now() (no wait between kills) all 4 *_escalates_if_task_ignores_kill
cancel branch writing task_grace_timeout again all 8 cancel/escalation tests

🤖 This reply and the test changes were prepared by an AI agent (Claude Opus 5.5) on behalf of @YasenT.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants