Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
fix(redis): fail the task of a worker whose running slot lease expired
A killed API process never reaches task_done(), so its task stayed in
processing forever and DELETE kept answering 409. The lease expiry already
frees the global slot; record which task each slot runs and fail the task
when its lease is gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
  • Loading branch information
HEOJUNFO and claude committed Nov 17, 2026
commit 660fee835a013a39a11d976db15902823f23794d
70 changes: 70 additions & 0 deletions app/controllers/manager/redis_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,27 @@
return 0
"""

# The lease only names a random slot token. Each slot also records the task it
# runs, so a slot whose lease ran out can be traced back to the task record that
# its worker left behind. Reading both keys in one script keeps a slot that is
# being released from looking expired.
_EXPIRED_RUNNING_TASKS_SCRIPT = """
local expired = {}
local owners = redis.call("HGETALL", KEYS[2])
for index = 1, #owners, 2 do
local deadline = redis.call("ZSCORE", KEYS[1], owners[index])
if (not deadline) or tonumber(deadline) <= tonumber(ARGV[1]) then
expired[#expired + 1] = owners[index]
expired[#expired + 1] = owners[index + 1]
end
end
return expired
"""

_RUNNING_SLOT_LEASE_SECONDS = 90.0
_RUNNING_SLOT_HEARTBEAT_SECONDS = 30.0
_QUEUE_DISPATCH_RETRY_SECONDS = 5.0
_WORKER_STOPPED_ERROR = "the worker process stopped before the task finished"


class RedisTaskManager(TaskManager):
Expand All @@ -96,6 +114,10 @@ def running_slots_key(self) -> str:
# semaphore must follow the selected queue namespace automatically.
return f"{self.queue}:running"

@property
def running_tasks_key(self) -> str:
return f"{self.queue}:running:tasks"

@staticmethod
def _now_ms() -> int:
return int(time.time() * 1000)
Expand Down Expand Up @@ -182,6 +204,7 @@ def stop_queue_dispatcher(self):
def _dispatch_queued_until_stopped(self):
while not self._dispatcher_stop.is_set():
try:
self.fail_tasks_of_expired_slots()
self.check_queue()
delay = self._next_queue_dispatch_delay()
except redis.RedisError as exc:
Expand All @@ -203,6 +226,47 @@ def _next_queue_dispatch_delay(self) -> float:
deadline_ms = earliest[0][1]
return max(0.01, (deadline_ms - self._now_ms()) / 1000)

def fail_tasks_of_expired_slots(self) -> int:
"""Fail the tasks whose worker stopped renewing its running slot.

A killed process never reaches task_done(), so the lease expiry frees
the global slot but the task record stays in processing and can never
be deleted. The same renewable lease that returns the capacity decides
here that the worker is gone.
"""
expired = self.redis_client.eval(
_EXPIRED_RUNNING_TASKS_SCRIPT,
2,
self.running_slots_key,
self.running_tasks_key,
self._now_ms(),
)
failed = 0
for index in range(0, len(expired or ()), 2):
token, task_id = (
value.decode("utf-8") if isinstance(value, bytes) else value
for value in expired[index : index + 2]
)
task = sm.state.get_task(task_id)
# A task that already reached a final state keeps its result: its
# worker finished and only failed to release the slot.
if task and task.get("state") == const.TASK_STATE_PROCESSING:
logger.error(
f"running slot lease expired, failing task: {task_id}, "
f"global slot: {token}"
)
sm.state.patch_task(
task_id,
state=const.TASK_STATE_FAILED,
failed_stage="worker",
error=_WORKER_STOPPED_ERROR,
)
failed += 1
# Forget the slot only after the record is settled, so a Redis
# error above leaves it for the next pass.
self.redis_client.hdel(self.running_tasks_key, token)
return failed

def check_queue(self):
while True:
token = uuid4().hex
Expand Down Expand Up @@ -237,6 +301,9 @@ def _start_reserved_task(self, token: str, task: Dict, restore_on_failure: bool)
self.current_tasks += 1
self._dispatch_context.slot_token = token
try:
task_id = kwargs.get("task_id") if isinstance(kwargs, dict) else None
if isinstance(task_id, str) and task_id:
self.redis_client.hset(self.running_tasks_key, token, task_id)
self.execute_task(func, *args, **kwargs)
except Exception:
with self.lock:
Expand Down Expand Up @@ -295,6 +362,9 @@ def _renew_slot_until_done(self, token: str, stop: threading.Event):

def _release_slot(self, token: str):
try:
# Drop the task mapping first: a slot that still names a task but
# has no lease is what fail_tasks_of_expired_slots() looks for.
self.redis_client.hdel(self.running_tasks_key, token)
self.redis_client.zrem(self.running_slots_key, token)
except redis.RedisError as exc:
# The lease will expire even if Redis is temporarily unavailable.
Expand Down
147 changes: 147 additions & 0 deletions test/services/test_redis_queue_admission.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@

from app.controllers.manager.base_manager import TaskQueueFullError
from app.controllers.manager.redis_manager import RedisTaskManager
from app.models import const
from app.models.schema import VideoParams
from app.services import state as sm
from app.services import task as tm


Expand All @@ -37,7 +39,152 @@ def setUp(self):
self.managers[0].redis_client.delete,
queue,
f"{queue}:running",
f"{queue}:running:tasks",
)
# The task records live in the configured state backend. Give every
# test its own so a record cannot leak into another test.
state_patcher = patch.object(sm, "state", sm.MemoryState())
self.state = state_patcher.start()
self.addCleanup(state_patcher.stop)

def _admit_task_whose_worker_dies(self, manager, task_id, progress=30):
"""Reserve a running slot the way add_task() does, without a worker."""
self.state.update_task(task_id, progress=progress)
with patch.object(manager, "execute_task"):
manager.add_task(
tm.start,
task_id=task_id,
params=VideoParams(video_subject="Coffee"),
)
owners = manager.redis_client.hgetall(manager.running_tasks_key)
tokens = [
token.decode("utf-8")
for token, owner in owners.items()
if owner.decode("utf-8") == task_id
]
self.assertEqual(len(tokens), 1)
return tokens[0]

def test_expired_slot_fails_the_task_its_worker_left_processing(self):
manager = self.managers[0]
manager.max_concurrent_tasks = 1
token = self._admit_task_whose_worker_dies(manager, "crashed")

# The lease is still valid: the worker may simply be busy.
self.assertEqual(manager.fail_tasks_of_expired_slots(), 0)
self.assertEqual(
self.state.get_task("crashed")["state"], const.TASK_STATE_PROCESSING
)

# No heartbeat renews the lease of a killed process.
manager.redis_client.zadd(manager.running_slots_key, {token: 0})
self.assertEqual(self.managers[1].fail_tasks_of_expired_slots(), 1)

task = self.state.get_task("crashed")
self.assertEqual(task["state"], const.TASK_STATE_FAILED)
self.assertEqual(task["failed_stage"], "worker")
self.assertIn("worker process stopped", task["error"])
self.assertEqual(task["progress"], 30)
self.assertFalse(tm.is_task_busy(task))
self.assertEqual(manager.redis_client.hlen(manager.running_tasks_key), 0)
self.assertEqual(manager.fail_tasks_of_expired_slots(), 0)

def test_task_is_failed_after_a_new_request_reclaimed_its_slot(self):
manager = self.managers[0]
for item in self.managers:
item.max_concurrent_tasks = 1
token = self._admit_task_whose_worker_dies(manager, "crashed")
manager.redis_client.zadd(manager.running_slots_key, {token: 0})

# Admission prunes the expired lease and gives the slot to the new
# task, so the crashed slot no longer has a deadline to compare.
replacement = self._admit_task_whose_worker_dies(
self.managers[1], "replacement", progress=0
)
self.assertIsNone(
manager.redis_client.zscore(manager.running_slots_key, token)
)

self.assertEqual(manager.fail_tasks_of_expired_slots(), 1)
self.assertEqual(
self.state.get_task("crashed")["state"], const.TASK_STATE_FAILED
)
self.assertEqual(
self.state.get_task("replacement")["state"],
const.TASK_STATE_PROCESSING,
)
self.assertEqual(
manager.redis_client.hkeys(manager.running_tasks_key),
[replacement.encode("utf-8")],
)

def test_expired_slot_keeps_the_result_of_a_finished_task(self):
manager = self.managers[0]
manager.max_concurrent_tasks = 1
token = self._admit_task_whose_worker_dies(manager, "finished")
# The worker finished, then lost Redis before releasing its slot.
self.state.update_task(
"finished",
state=const.TASK_STATE_COMPLETE,
progress=100,
videos=["final-1.mp4"],
)
manager.redis_client.zadd(manager.running_slots_key, {token: 0})

self.assertEqual(manager.fail_tasks_of_expired_slots(), 0)

task = self.state.get_task("finished")
self.assertEqual(task["state"], const.TASK_STATE_COMPLETE)
self.assertEqual(task["videos"], ["final-1.mp4"])
self.assertNotIn("error", task)
self.assertEqual(manager.redis_client.hlen(manager.running_tasks_key), 0)

def test_finished_worker_leaves_no_running_task_behind(self):
manager = self.managers[0]
manager.max_concurrent_tasks = 1
self.state.update_task("done")

def finish(task_id):
self.state.update_task(
task_id, state=const.TASK_STATE_COMPLETE, progress=100
)

manager.add_task(finish, task_id="done")
deadline = time.monotonic() + 5
while manager.current_tasks and time.monotonic() < deadline:
time.sleep(0.01)

self.assertEqual(manager.current_tasks, 0)
self.assertEqual(manager.redis_client.hlen(manager.running_tasks_key), 0)
self.assertEqual(manager.redis_client.zcard(manager.running_slots_key), 0)
self.assertEqual(manager.fail_tasks_of_expired_slots(), 0)
self.assertEqual(
self.state.get_task("done")["state"], const.TASK_STATE_COMPLETE
)

def test_restart_dispatcher_fails_the_task_of_a_crashed_worker(self):
manager = self.managers[0]
manager.max_concurrent_tasks = 1
token = self._admit_task_whose_worker_dies(manager, "crashed")
manager.redis_client.zadd(manager.running_slots_key, {token: 0})

# A replacement process only runs its lifespan startup.
restarted = self.managers[1]
restarted.max_concurrent_tasks = 1
restarted.resume_queued_tasks()
restarted.start_queue_dispatcher()
self.addCleanup(restarted.stop_queue_dispatcher)

deadline = time.monotonic() + 2
while (
self.state.get_task("crashed")["state"] == const.TASK_STATE_PROCESSING
and time.monotonic() < deadline
):
time.sleep(0.01)

task = self.state.get_task("crashed")
self.assertEqual(task["state"], const.TASK_STATE_FAILED)
self.assertEqual(task["failed_stage"], "worker")

def test_running_limit_is_shared_across_manager_instances(self):
for manager in self.managers:
Expand Down
Loading