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
Prev Previous commit
fix(redis): fail a task whose directory lock cannot be taken
With a storage root that is not writable, creating storage/task_locks
raised PermissionError in the worker before the pipeline started. The
exception skipped everything except task_done(), which removed the slot
and its task entry, so the task stayed in processing and nothing was left
for the expiry check to find. A lock that could not be acquired was only
logged and the pipeline ran without it.

The worker now fails the task when the lock directory cannot be created
or the lock cannot be acquired, and does not run the pipeline. The
failure is written through the slot token, before the slot is released.

A deletion that cannot create or open the lock goes ahead when the lock
file does not exist: a worker runs a task only while it holds that file.
It still refuses when the file exists and cannot be opened. Before, the
API answered 500 and the WebUI raised.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
  • Loading branch information
HEOJUNFO and claude committed Nov 23, 2026
commit aec13dcf9abcfd85e6ea682978d173328d8cc905
39 changes: 25 additions & 14 deletions app/controllers/manager/redis_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
import threading
import time
from contextlib import contextmanager
from contextlib import ExitStack
from typing import Dict
from uuid import uuid4

Expand Down Expand Up @@ -363,8 +363,7 @@ def _run_reserved_task(self, token: str, func, *args, **kwargs):
if task_id is None:
func(*args, **kwargs)
else:
with self._owned_task(task_id, token):
func(*args, **kwargs)
self._run_owned_task(task_id, token, func, *args, **kwargs)
finally:
stop_heartbeat.set()
self.task_done()
Expand All @@ -375,22 +374,34 @@ def _task_id_of(kwargs) -> str | None:
task_id = kwargs.get("task_id") if isinstance(kwargs, dict) else None
return task_id if isinstance(task_id, str) and task_id else None

@contextmanager
def _owned_task(self, task_id: str, token: str):
def _run_owned_task(self, task_id: str, token: str, func, /, *args, **kwargs):
"""Run a task as the worker that holds ``token``.

State writes go through the token for as long as the task runs, and
this process holds the task directory, so a deletion waits for it.
"""
with tm.task_directory_lock(task_id) as held:
if not held:
# Running without the lock only loses the deletion guard.
logger.error(f"failed to lock the directory of task {task_id}")
sm.state.bind_task_owner(task_id, self.running_tasks_key, token)
try:
yield
finally:
sm.state.unbind_task_owner(task_id)
sm.state.bind_task_owner(task_id, self.running_tasks_key, token)
try:
with ExitStack() as held:
try:
held.enter_context(tm.task_directory_lock(task_id))
except tm.TaskDirectoryLockError as exc:
# Without the lock a deletion cannot see that this process
# writes the directory, so the task is not run. It is
# failed here, while the token still owns it: the caller
# releases the slot only after this returns, and nothing
# looks at a task whose slot is already gone.
logger.error(f"task {task_id} was not started: {exc}")
sm.state.patch_task(
task_id,
state=const.TASK_STATE_FAILED,
failed_stage="worker",
error=str(exc),
)
return
func(*args, **kwargs)
finally:
sm.state.unbind_task_owner(task_id)

def _renew_slot_until_done(self, token: str, stop: threading.Event):
while not stop.wait(_RUNNING_SLOT_HEARTBEAT_SECONDS):
Expand Down
65 changes: 54 additions & 11 deletions app/services/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,26 +125,49 @@ def _get_video_music_prompt(params: VideoParams) -> str:
return prompt


class TaskDirectoryLockError(RuntimeError):
"""A task's directory lock was not taken.

``held`` is True when another process holds it, and False when the lock
could not be created or opened at all.
"""

def __init__(self, lock_file: str, cause: Exception):
self.lock_file = lock_file
self.held = isinstance(cause, FileLockTimeout)
reason = (
"another process holds it"
if self.held
else f"{type(cause).__name__}: {cause}"
)
super().__init__(f"cannot lock the task directory with {lock_file}: {reason}")


@contextmanager
def task_directory_lock(task_id: str, timeout: float = 0):
"""Hold a task's directory against other processes; yield whether we got it.
"""Hold a task's directory against other processes inside the ``with`` block.

A queue worker holds it while it runs the task. The lock belongs to the
operating system: it is gone as soon as the holding process is killed, and
still held while that process is only paused.

Raises TaskDirectoryLockError, and does not run the block, when the lock
is not taken.
"""
# Task IDs reach the delete endpoint as request input; never let one
# choose the file name.
name = hashlib.sha256(task_id.encode("utf-8")).hexdigest()
lock_file = path.join(utils.storage_dir("task_locks", create=True), f"{name}.lock")
lock = FileLock(lock_file)
lock_file = path.join(utils.storage_dir("task_locks"), f"{name}.lock")
try:
# Creating the directory is part of taking the lock. It fails when the
# storage root is not writable, and has to end like any other failure.
os.makedirs(path.dirname(lock_file), exist_ok=True)
lock = FileLock(lock_file)
lock.acquire(timeout=timeout)
except (FileLockTimeout, OSError):
yield False
return
except (FileLockTimeout, OSError) as exc:
raise TaskDirectoryLockError(lock_file, exc) from exc
try:
yield True
yield
finally:
lock.release()
try:
Expand All @@ -162,10 +185,30 @@ def is_task_directory_held(task_id: str) -> bool:
again when it resumes. Once the directory is free it stays free: a task in
a final state is never handed to a worker again.
"""
# A concurrent deletion of the same task asks the same question and holds
# the lock only for that instant, so wait that out instead of refusing.
with task_directory_lock(task_id, timeout=_TASK_DIRECTORY_PROBE_SECONDS) as free:
return not free
try:
# A concurrent deletion of the same task asks the same question and
# holds the lock only for that instant, so wait that out instead of
# refusing.
with task_directory_lock(task_id, timeout=_TASK_DIRECTORY_PROBE_SECONDS):
return False
except TaskDirectoryLockError as exc:
if exc.held:
return True
# This process cannot create or open the lock. A worker runs a task
# only while it holds that lock, and its lock file stays in place for
# as long as it does. So with no lock file there is no worker to wait
# for, and a storage root that is not writable must not make every
# task undeletable. A lock file that exists but cannot be opened may
# belong to a live worker.
try:
os.lstat(exc.lock_file)
except (FileNotFoundError, NotADirectoryError):
logger.warning(f"deleting without the directory lock: {exc}")
return False
except OSError:
pass
logger.error(f"cannot tell whether a worker holds the task: {exc}")
return True


def is_task_busy(task: dict | None) -> bool:
Expand Down
92 changes: 92 additions & 0 deletions test/services/test_controller_video.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import errno
import os
import shutil
import tempfile
Expand Down Expand Up @@ -573,6 +574,61 @@ def test_delete_refuses_task_whose_directory_a_worker_still_holds(self):
rmtree.assert_not_called()
delete_task.assert_not_called()

def test_delete_with_an_unusable_lock_depends_on_the_lock_file(self):
"""A lock this process cannot open blocks deletion only if its file exists."""
failed_task = {
"task_id": "unlockable-task",
"state": const.TASK_STATE_FAILED,
"progress": 0,
"failed_stage": "worker",
}

for lock_file_exists, expected_status in ((False, 200), (True, 409)):
with (
self.subTest(lock_file_exists=lock_file_exists),
tempfile.TemporaryDirectory() as storage,
):

def refused_lock(lock_file):
# No worker runs a task without holding this file, so a
# missing file means no worker; an existing one may be held.
if lock_file_exists:
Path(lock_file).parent.mkdir(exist_ok=True)
Path(lock_file).touch()
lock = MagicMock()
lock.acquire.side_effect = PermissionError(
errno.EACCES, "Permission denied", lock_file
)
return lock

with (
patch.object(
video_controller.utils,
"storage_dir",
side_effect=lambda sub_dir="", create=False: os.path.join(
storage, sub_dir
),
),
patch.object(
video_controller.tm, "FileLock", side_effect=refused_lock
),
patch.object(
video_controller.sm.state, "get_task", return_value=failed_task
),
patch.object(
video_controller.sm.state, "delete_task"
) as delete_task,
):
try:
status = video_controller.delete_video(
self._request(), task_id="unlockable-task"
)["status"]
except HttpException as exc:
status = exc.status_code

self.assertEqual(status, expected_status)
self.assertEqual(delete_task.call_count, int(expected_status == 200))

def test_get_and_delete_missing_task_return_404(self):
"""查询或删除未知任务都应返回一致的 404,而不是空成功响应。"""
with patch.object(video_controller.sm.state, "get_task", return_value=None):
Expand Down Expand Up @@ -704,6 +760,42 @@ def test_deleted_task_lookup_returns_404(self):

self.assertEqual(lookup_response.status_code, 404)

def test_delete_failed_task_when_the_lock_directory_cannot_be_created(self):
"""A storage root that is not writable must not turn deletion into a 500."""

task_id = "http-delete-unlockable-task"
task_dir = utils.task_dir(task_id)
Path(task_dir, "script.json").write_text("{}", encoding="utf-8")
# What a queue worker leaves behind when it could not lock the task.
sm.state.update_task(
task_id,
state=const.TASK_STATE_FAILED,
failed_stage="worker",
error="cannot lock the task directory",
)
lock_directory = utils.storage_dir("task_locks")
makedirs = os.makedirs

def refusing_makedirs(name, *args, **kwargs):
# Root ignores chmod, so raise what a read-only storage root does.
if os.fspath(name) == lock_directory:
raise PermissionError(errno.EACCES, "Permission denied", lock_directory)
return makedirs(name, *args, **kwargs)

client = TestClient(asgi.app, raise_server_exceptions=False)
try:
with patch.object(os, "makedirs", refusing_makedirs):
response = client.delete(f"/api/v1/tasks/{task_id}")
lookup_response = client.get(f"/api/v1/tasks/{task_id}")
directory_left = os.path.exists(task_dir)
finally:
shutil.rmtree(task_dir, ignore_errors=True)
sm.state.delete_task(task_id)

self.assertEqual(response.status_code, 200)
self.assertEqual(lookup_response.status_code, 404)
self.assertFalse(directory_left)


class TestVideoControllerFiles(unittest.TestCase):
@staticmethod
Expand Down
Loading
Loading