diff --git a/app/services/task.py b/app/services/task.py index aa6a775403..c02728eeb9 100644 --- a/app/services/task.py +++ b/app/services/task.py @@ -114,6 +114,72 @@ 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 +# A real pipeline run can legitimately take longer than +# _ACTIVE_LOCK_STALE_SECONDS -- age alone can't distinguish "still +# running, just slow" from "the process that held this died". start() +# below refreshes the lock's mtime on this interval for the whole +# duration of the run (a renewable lease, not a one-shot timestamp), so +# a genuinely alive task's lock never actually reaches the staleness +# cutoff above. Comfortably inside that cutoff so a single missed tick +# (GC pause, a loaded host) still leaves real margin before the lock +# would be treated as stale. +_ACTIVE_LOCK_HEARTBEAT_SECONDS = 300 + + +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 _active_lock_heartbeat_loop(task_id: str, stop_event: threading.Event) -> None: + # Event.wait() returns True the moment stop_event is set, instead of + # always sleeping the full interval -- so clearing the lock on a fast + # pipeline run isn't delayed by up to _ACTIVE_LOCK_HEARTBEAT_SECONDS. + while not stop_event.wait(_ACTIVE_LOCK_HEARTBEAT_SECONDS): + _mark_task_active(task_id) + + +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: @@ -1921,6 +1987,20 @@ def start( ``allow_server_file_input`` 只供本机 CLI 使用。HTTP API 和 WebUI 必须保持 默认值,让自定义音频始终受当前任务目录约束。 """ + _mark_task_active(task_id) + # Renews the lock on _ACTIVE_LOCK_HEARTBEAT_SECONDS for as long as this + # run lasts, so is_task_actively_running() never treats a genuinely + # alive task as stale just because it's taking longer than + # _ACTIVE_LOCK_STALE_SECONDS -- see both constants' comments above. + # daemon=True: if the process itself is killed, this thread must never + # be what keeps it alive. + heartbeat_stop = threading.Event() + heartbeat_thread = threading.Thread( + target=_active_lock_heartbeat_loop, + args=(task_id, heartbeat_stop), + daemon=True, + ) + heartbeat_thread.start() try: return _run_pipeline( task_id, @@ -1942,6 +2022,10 @@ def start( "pipeline", f"{type(exc).__name__}: {exc}", ) + finally: + heartbeat_stop.set() + heartbeat_thread.join(timeout=5) + _clear_task_active(task_id) if __name__ == "__main__": diff --git a/test/services/test_task_active_lock.py b/test/services/test_task_active_lock.py new file mode 100644 index 0000000000..e2870014a3 --- /dev/null +++ b/test/services/test_task_active_lock.py @@ -0,0 +1,154 @@ +import os +import sys +import threading +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_heartbeat_loop_refreshes_the_lock_on_each_tick_until_stopped(self): + # Unit-level check of the loop itself, isolated from start()/ + # threading timing: a fake clock lets the wait()-then-tick + # sequence be asserted deterministically rather than raced against + # real time. + stop_event = threading.Event() + calls = [] + + def fake_mark_task_active(task_id): + calls.append(task_id) + if len(calls) >= 3: + stop_event.set() + + with mock.patch.object(tm, "_mark_task_active", side_effect=fake_mark_task_active): + with mock.patch.object(tm, "_ACTIVE_LOCK_HEARTBEAT_SECONDS", 0): + tm._active_lock_heartbeat_loop(self.task_id, stop_event) + + self.assertEqual(calls, [self.task_id] * 3) + + def test_start_keeps_a_long_running_task_s_lock_fresh_past_the_stale_cutoff(self): + # Maintainer's second real repro: backdate the lock's mtime past + # the staleness cutoff while the pipeline is still genuinely + # running (they simulated the elapsed hour this same way, without + # actually waiting it out). Before the heartbeat fix, + # is_task_actively_running() would then incorrectly report False + # for the rest of the run even though the worker was still alive. + pipeline_started = threading.Event() + heartbeat_ticked_during_pipeline = threading.Event() + + real_mark_task_active = tm._mark_task_active + + def mark_task_active_and_signal(task_id): + real_mark_task_active(task_id) + # The very first call happens inside start(), before the + # pipeline below even begins -- only a call that lands AFTER + # the pipeline has started counts as a real heartbeat tick. + if pipeline_started.is_set(): + heartbeat_ticked_during_pipeline.set() + + def long_pipeline(*_args, **_kwargs): + pipeline_started.set() + 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), + "sanity check: the backdated lock must read as stale before any heartbeat fires", + ) + self.assertTrue( + heartbeat_ticked_during_pipeline.wait(timeout=2), + "a real heartbeat tick must fire while the pipeline is still running", + ) + self.assertTrue( + tm.is_task_actively_running(self.task_id), + "a live task's lock must be refreshed before the stale cutoff is " + "reached, even though its age alone would otherwise say it's stale", + ) + return "ok" + + with mock.patch.object(tm, "_ACTIVE_LOCK_HEARTBEAT_SECONDS", 0.05): + with mock.patch.object( + tm, "_mark_task_active", side_effect=mark_task_active_and_signal + ): + with mock.patch.object(tm, "_run_pipeline", side_effect=long_pipeline): + result = tm.start(self.task_id, params=mock.Mock()) + + self.assertEqual(result, "ok") + + 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() diff --git a/test/services/test_webui_headless_task_actions.py b/test/services/test_webui_headless_task_actions.py index 4760d3958f..e0a8401f53 100644 --- a/test/services/test_webui_headless_task_actions.py +++ b/test/services/test_webui_headless_task_actions.py @@ -31,7 +31,14 @@ def headless_task_app(tmp_path, monkeypatch): video_file = task_dir / "final-1.mp4" video_file.write_bytes(b"test video payload") - monkeypatch.setattr(utils, "task_dir", lambda: str(tasks_dir)) + # utils.task_dir(sub_dir="") takes an optional task_id/sub_dir -- the + # real signature callers (including _active_lock_path()) rely on to + # get a specific task's own directory, not just the tasks root. A + # zero-arg stub broke with a TypeError the moment that real call site + # started passing task_id through. + monkeypatch.setattr( + utils, "task_dir", lambda sub_dir="": str(tasks_dir / sub_dir) if sub_dir else str(tasks_dir) + ) monkeypatch.setattr(sm.state, "get_all_tasks", lambda *_args, **_kwargs: ([], 0)) monkeypatch.setattr(sys, "platform", "linux") monkeypatch.delenv("DISPLAY", raising=False) diff --git a/test/services/test_webui_task.py b/test/services/test_webui_task.py index 58f395222a..2985dcabdc 100644 --- a/test/services/test_webui_task.py +++ b/test/services/test_webui_task.py @@ -160,7 +160,14 @@ def test_webui_delete_keeps_task_state_when_file_removal_fails(tmp_path): namespace = { "_active_generation_tasks": lambda: {}, "sm": SimpleNamespace(state=state), - "tm": SimpleNamespace(is_task_busy=lambda _task: False), + "tm": SimpleNamespace( + is_task_busy=lambda _task: False, + # _delete_task() now also consults a disk-based cross-process + # lock (see test_task_active_lock.py) alongside the in-process + # checks above -- this test is about a failed file removal, not + # about an active-elsewhere task, so it stays not-running. + is_task_actively_running=lambda _task_id: False, + ), "utils": SimpleNamespace(task_dir=lambda: str(tmp_path / "tasks")), "shutil": SimpleNamespace(rmtree=remove_directory), "logger": MagicMock(), diff --git a/webui/Main.py b/webui/Main.py index 188fd1ea33..15e65ae846 100644 --- a/webui/Main.py +++ b/webui/Main.py @@ -1209,10 +1209,30 @@ def _delete_task(task_id, task_path, task_state=None): task_snapshot = dict(current_task or {}) task_snapshot.setdefault("state", task_state) - if task_id in _active_generation_tasks(): + is_active = task_id in _active_generation_tasks() + if is_active: task_snapshot["state"] = const.TASK_STATE_PROCESSING - if tm.is_task_busy(task_snapshot): + # 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 @@ -1293,7 +1313,24 @@ def _render_task_table(filtered_tasks, key_prefix): task_id = task["task_id"] has_video = bool(task["video_file"] and os.path.isfile(task["video_file"])) is_processing = _task_state_filter_key(task) == "processing" - is_busy = is_processing or tm.is_task_busy(task) + # History-sourced rows (source == "history") have no live tracked + # record by construction -- see _collect_task_summaries(), which + # only keeps a "history" entry when no runtime/active record + # overrode it. is_task_busy()'s conservative "unparseable state + # means busy" rule is for tracked records whose state could not + # 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_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( os.path.join(task["task_path"], "script.json") )