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
Next Next commit
fix(task): block deletion of tasks actively running in another process
With the default enable_redis=false config, each process (API, WebUI,
CLI) keeps its own isolated in-memory task registry via MemoryState.
The previous commit's fix only checked THIS process's view of a task
(sm.state.get_task() and the WebUI session's active-generation
registry), so a task started in a different process -- not yet
produced a video, therefore showing up here as source="history",
state=None -- looked identical to a genuinely idle orphaned task.

Added a disk-based lock (app/services/task.py: _mark_task_active() /
_clear_task_active(), held for the whole duration of start(), the
single entry point every caller's pipeline run goes through) that any
process can see, since the task directory is the one thing they all
share without Redis. is_task_actively_running() checks this lock and
is now consulted alongside the existing in-process checks at both
WebUI call sites. A stale lock (left behind by a process that died
without reaching start()'s finally block) expires after an hour so a
crash doesn't block deletion forever either.

Added test/services/test_task_active_lock.py, including a test that
pauses start() mid-pipeline (mocking _run_pipeline) and asserts the
lock is held for that whole window and cleared afterward, matching
the reported repro.
  • Loading branch information
kapil971390 committed Oct 25, 2026
commit b6698a0f9fcc9f5365cb05358f595a61a74bcf3e
51 changes: 51 additions & 0 deletions app/services/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,54 @@ def _get_video_music_prompt(params: VideoParams) -> str:
return prompt


_ACTIVE_LOCK_FILENAME = ".active.lock"
# Generous upper bound for one full pipeline run. A process that dies
# without reaching the finally block (kill -9, OOM, host reboot) leaves
# a stale lock behind; this cutoff lets a task recover from that instead
# of staying falsely "active" forever.
_ACTIVE_LOCK_STALE_SECONDS = 3600


def _active_lock_path(task_id: str) -> str:
# task_dir() creates the directory if it doesn't exist yet.
return os.path.join(utils.task_dir(task_id), _ACTIVE_LOCK_FILENAME)


def _mark_task_active(task_id: str) -> None:
try:
with open(_active_lock_path(task_id), "w") as f:
f.write(str(os.getpid()))
except OSError as e:
logger.warning(f"failed to write active-task lock for {task_id}: {e}")


def _clear_task_active(task_id: str) -> None:
try:
os.remove(_active_lock_path(task_id))
except FileNotFoundError:
pass
except OSError as e:
logger.warning(f"failed to remove active-task lock for {task_id}: {e}")


def is_task_actively_running(task_id: str) -> bool:
"""
Cross-process liveness signal, independent of in-memory task state.

With the default enable_redis=false config, each process (API, WebUI,
CLI) keeps its own isolated in-memory task registry, so a task started
in one process is invisible to is_task_busy() calls made from another.
This lock file is the one signal every process can see, since the task
directory on disk is the only thing they actually share.
"""
lock_path = _active_lock_path(task_id)
try:
mtime = os.path.getmtime(lock_path)
except OSError:
return False
return (time.time() - mtime) < _ACTIVE_LOCK_STALE_SECONDS


def is_task_busy(task: dict | None) -> bool:
"""判断任务是否仍在生成或发布,供所有删除入口复用。"""
if not task:
Expand Down Expand Up @@ -1921,6 +1969,7 @@ def start(
``allow_server_file_input`` 只供本机 CLI 使用。HTTP API 和 WebUI 必须保持
默认值,让自定义音频始终受当前任务目录约束。
"""
_mark_task_active(task_id)
try:
return _run_pipeline(
task_id,
Expand All @@ -1942,6 +1991,8 @@ def start(
"pipeline",
f"{type(exc).__name__}: {exc}",
)
finally:
_clear_task_active(task_id)


if __name__ == "__main__":
Expand Down
86 changes: 86 additions & 0 deletions test/services/test_task_active_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import os
import sys
import time
import unittest
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from app.services import task as tm


class TestTaskActiveLockCrossProcess(unittest.TestCase):
"""
With the default enable_redis=false config, each process (API, WebUI,
CLI) keeps its own isolated in-memory task registry. A task started by
one process is invisible to is_task_busy() calls made from another --
the on-disk lock written by _mark_task_active()/_clear_task_active()
(used by start()) is the one signal every process can see.
"""

def setUp(self):
self.task_id = f"test-active-lock-{int(time.time() * 1000)}"

def tearDown(self):
tm._clear_task_active(self.task_id)

def test_no_lock_means_not_actively_running(self):
self.assertFalse(tm.is_task_actively_running(self.task_id))

def test_lock_present_means_actively_running(self):
tm._mark_task_active(self.task_id)
self.assertTrue(tm.is_task_actively_running(self.task_id))

def test_clear_removes_the_lock(self):
tm._mark_task_active(self.task_id)
tm._clear_task_active(self.task_id)
self.assertFalse(tm.is_task_actively_running(self.task_id))

def test_stale_lock_is_not_treated_as_active(self):
# A process that dies without reaching start()'s finally block
# (kill -9, OOM, host reboot) leaves the lock file behind forever.
tm._mark_task_active(self.task_id)
stale_time = time.time() - (tm._ACTIVE_LOCK_STALE_SECONDS + 60)
os.utime(tm._active_lock_path(self.task_id), (stale_time, stale_time))
self.assertFalse(tm.is_task_actively_running(self.task_id))

def test_start_holds_the_lock_for_the_whole_pipeline_duration(self):
# Models the maintainer's repro: start() is paused mid-pipeline in
# one process; a different process (or this same test, standing in
# for it) must see the task as actively running for that whole
# window, and see it clear once the pipeline returns.
release_pipeline = mock.Mock()

def paused_pipeline(*_args, **_kwargs):
self.assertTrue(
tm.is_task_actively_running(self.task_id),
"lock must already be held once the pipeline starts running",
)
release_pipeline()
return "ok"

with mock.patch.object(tm, "_run_pipeline", side_effect=paused_pipeline):
result = tm.start(self.task_id, params=mock.Mock())

release_pipeline.assert_called_once()
self.assertEqual(result, "ok")
self.assertFalse(
tm.is_task_actively_running(self.task_id),
"lock must be cleared once start() returns",
)

def test_start_clears_the_lock_even_on_pipeline_exception(self):
with mock.patch.object(tm, "_run_pipeline", side_effect=RuntimeError("boom")):
with mock.patch.object(tm, "_mark_task_failed") as mark_failed:
tm.start(self.task_id, params=mock.Mock())
mark_failed.assert_called_once()

self.assertFalse(
tm.is_task_actively_running(self.task_id),
"lock must be cleared even when the pipeline raises",
)


if __name__ == "__main__":
unittest.main()
36 changes: 27 additions & 9 deletions webui/Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1213,14 +1213,25 @@ def _delete_task(task_id, task_path, task_state=None):
if is_active:
task_snapshot["state"] = const.TASK_STATE_PROCESSING

# A task with no live tracked record (current_task is None) and not in
# this session's active-generation registry has nothing that could be
# processing or cross-posting it. is_task_busy()'s conservative
# "unparseable state means busy" rule (including state=None) is meant
# for tracked records whose state could not be read correctly -- it
# was never meant to cover disk-only history entries that were never
# tracked in the first place, whose UI-assigned state=None
# (_scan_history_tasks) has no bearing on whether anything is running.
# With the default enable_redis=false config, each process (API,
# WebUI, CLI) keeps its own isolated in-memory task registry, so
# current_task/is_active above only see tasks THIS process started.
# is_task_actively_running() checks a disk-based lock every process
# can see instead, so a task started elsewhere (e.g. via the API
# while this is the WebUI process) still blocks deletion here.
if tm.is_task_actively_running(task_id):
logger.warning(f"refused to delete actively running task: {task_id}")
return False

# A task with no live tracked record (current_task is None), not in
# this session's active-generation registry, and with no active
# cross-process lock has nothing that could be processing or cross-
# posting it. is_task_busy()'s conservative "unparseable state means
# busy" rule (including state=None) is meant for tracked records
# whose state could not be read correctly -- it was never meant to
# cover disk-only history entries that were never tracked in the
# first place, whose UI-assigned state=None (_scan_history_tasks) has
# no bearing on whether anything is running.
if (current_task is not None or is_active) and tm.is_task_busy(task_snapshot):
logger.warning(f"refused to delete running task: {task_id}")
return False
Expand Down Expand Up @@ -1310,7 +1321,14 @@ def _render_task_table(filtered_tasks, key_prefix):
# be read, not for these -- without this, every history task
# with no video file (state=None, see _scan_history_tasks)
# permanently shows a disabled Delete button.
is_busy = is_processing or (
#
# is_task_actively_running() still applies on top of that: with
# the default enable_redis=false config, a task started by a
# different process (e.g. the API) is invisible to this
# process's in-memory state and would otherwise look exactly
# like an idle history row. The disk-based lock is the one
# signal every process can see.
is_busy = is_processing or tm.is_task_actively_running(task_id) or (
task.get("source") != "history" and tm.is_task_busy(task)
)
has_restore_data = os.path.isfile(
Expand Down
Loading