videogen/test/services/test_state.py
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

445 lines
17 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import sys
import threading
import unittest
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from app.models import const
from app.services.state import MemoryState, RedisState
class _FakeRedis:
"""
最小 Redis SCAN 模拟。
`batches` 是一个“批次序列的序列”:外层列表的每个元素代表一次完整扫描
(从 cursor=0 到 cursor=0)看到的批次顺序。每调用一次 `scan(0, ...)`
开始新的扫描周期时,会按顺序取下一个预设的批次序列——用来模拟 Redis
SCAN 在哈希表 rehash(例如 Redis 重启/resize)后,两次独立扫描可能
看到完全不同遍历顺序、甚至重复返回同一个 key 的真实行为。
如果调用次数超过预设周期数,复用最后一个周期(保持确定性,不越界)。
"""
def __init__(self, batches):
# 兼容旧用法:传入单个批次序列(非嵌套)时,视为只有一种扫描顺序。
if batches and not isinstance(batches[0][0] if batches[0] else None, list):
batches = [batches]
self.scan_cycles = batches
self.scan_types = []
self._cycle_index = -1
self._current_cycle = None
self.data = {}
for index, key in enumerate(
dict.fromkeys(
key for cycle in batches for batch in cycle for key in batch
)
):
self.data[key] = {
b"task_id": key,
b"state": b"1",
b"progress": str(index).encode("utf-8"),
}
def scan(self, cursor, count, _type=None):
self.scan_types.append(_type)
if cursor == 0:
self._cycle_index = min(self._cycle_index + 1, len(self.scan_cycles) - 1)
self._current_cycle = self.scan_cycles[self._cycle_index]
batch_index = 0
else:
batch_index = int(cursor)
next_cursor = batch_index + 1
if next_cursor >= len(self._current_cycle):
next_cursor = 0
return next_cursor, self._current_cycle[batch_index]
def hgetall(self, key):
if isinstance(key, str):
key = key.encode("utf-8")
return self.data[key]
def exists(self, key):
if isinstance(key, str):
key = key.encode("utf-8")
return key in self.data
def hset(self, key, field=None, value=None, mapping=None):
if isinstance(key, str):
key = key.encode("utf-8")
target = self.data.setdefault(key, {})
if mapping:
target.update(
{
str(item_key).encode("utf-8"): str(item_value).encode("utf-8")
for item_key, item_value in mapping.items()
}
)
elif field is not None:
target[str(field).encode("utf-8")] = str(value).encode("utf-8")
def eval(self, script, numkeys, key, *arguments):
if isinstance(key, str):
key = key.encode("utf-8")
if key not in self.data:
return 0
target = self.data[key]
for index in range(0, len(arguments), 2):
field = str(arguments[index]).encode("utf-8")
value = str(arguments[index + 1]).encode("utf-8")
target[field] = value
return 1
class TestMemoryState(unittest.TestCase):
def test_get_task_and_get_all_tasks_return_isolated_snapshots(self):
state = MemoryState()
state.update_task(
"task-1",
state=const.TASK_STATE_PROCESSING,
progress=25,
videos=["first.mp4"],
)
task = state.get_task("task-1")
task["videos"].append("mutated.mp4")
tasks, total = state.get_all_tasks(page=1, page_size=10)
tasks[0]["videos"].append("mutated-again.mp4")
self.assertEqual(total, 1)
self.assertEqual(state.get_task("task-1")["videos"], ["first.mp4"])
def test_get_all_task_ids_returns_a_snapshot(self):
state = MemoryState()
state.update_task("task-1", state=const.TASK_STATE_PROCESSING, progress=10)
state.update_task("task-2", state=const.TASK_STATE_PROCESSING, progress=20)
ids = state.get_all_task_ids()
self.assertEqual(sorted(ids), ["task-1", "task-2"])
# 修改快照不能影响内部状态。
ids.append("task-3")
self.assertEqual(sorted(state.get_all_task_ids()), ["task-1", "task-2"])
def test_concurrent_memory_updates_are_preserved(self):
state = MemoryState()
thread_count = 5
tasks_per_thread = 50
def update_tasks(thread_index):
for task_index in range(tasks_per_thread):
state.update_task(
f"task-{thread_index}-{task_index}",
state=const.TASK_STATE_PROCESSING,
progress=task_index,
)
threads = [
threading.Thread(target=update_tasks, args=(thread_index,))
for thread_index in range(thread_count)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
tasks, total = state.get_all_tasks(page=1, page_size=thread_count * tasks_per_thread)
self.assertEqual(total, thread_count * tasks_per_thread)
self.assertEqual(len(tasks), total)
def test_patch_task_preserves_generated_outputs(self):
"""异步发布更新不能覆盖已经完成的视频任务字段。"""
state = MemoryState()
state.update_task(
"task-1",
state=const.TASK_STATE_COMPLETE,
progress=100,
videos=["final.mp4"],
)
patched = state.patch_task(
"task-1",
cross_post_state=const.CROSS_POST_STATE_COMPLETE,
cross_post_results=[{"success": True}],
)
self.assertTrue(patched)
self.assertEqual(
state.get_task("task-1"),
{
"task_id": "task-1",
"state": const.TASK_STATE_COMPLETE,
"progress": 100,
"videos": ["final.mp4"],
"cross_post_state": const.CROSS_POST_STATE_COMPLETE,
"cross_post_results": [{"success": True}],
},
)
self.assertFalse(state.patch_task("missing", value="ignored"))
class TestRedisState(unittest.TestCase):
@staticmethod
def _key(index: int) -> bytes:
# 零填充保证按字节排序与数字顺序一致,方便断言;真实 task_id 是
# UUID,排序只是为了获得与 SCAN 遍历顺序无关的稳定顺序,不要求有
# 数字含义。
return f"task:{index:03d}".encode("utf-8")
def _build_state(self, batch_sizes, cycles: int = 1):
"""
构造一个 `_FakeRedis`。
`batch_sizes` 描述一次扫描内每批返回多少个 key(用于复现 PR #890
的批次偏移场景)。`cycles` 大于 1 时,为同一组 key 生成多个不同的
批次顺序,模拟 Redis 哈希表 rehash(重启/resize)后同一批 key 以
不同顺序被 SCAN 返回。
"""
total = sum(batch_sizes)
keys = [self._key(i) for i in range(total)]
cycle_list = []
for cycle_index in range(cycles):
ordered_keys = self._cycle_order(keys, cycle_index)
batches = []
offset = 0
for batch_size in batch_sizes:
batches.append(ordered_keys[offset : offset + batch_size])
offset += batch_size
cycle_list.append(batches)
state = RedisState.__new__(RedisState)
state._redis = _FakeRedis(cycle_list)
return state
@staticmethod
def _cycle_order(keys, cycle_index: int):
if cycle_index == 0:
return list(keys)
# 确定性地“打乱”顺序,而不是随机,保证测试可重复:按一个与
# cycle_index 相关的偏移量做旋转,模拟 rehash 后不同的遍历顺序。
offset = (cycle_index * 7 + 3) % max(len(keys), 1)
return keys[offset:] + keys[:offset]
def test_get_all_tasks_paginates_across_scan_batches(self):
"""
Redis SCAN 分批返回 key 时,分页切片必须按当前批次起始位置计算。
这个用例复现 PR #890 描述的 18 条任务、page_size=10 场景:
第一批 10 条,第二批 8 条。旧逻辑第一页会返回空列表,第二页
只返回 2 条;修复后第一页返回 10 条,第二页返回剩余 8 条。
"""
state = self._build_state([10, 8])
first_page, first_total = state.get_all_tasks(page=1, page_size=10)
second_page, second_total = state.get_all_tasks(page=2, page_size=10)
self.assertEqual(first_total, 18)
self.assertEqual(second_total, 18)
self.assertEqual(len(first_page), 10)
self.assertEqual(len(second_page), 8)
self.assertEqual(
[task["task_id"] for task in first_page],
[self._key(i).decode("utf-8") for i in range(10)],
)
self.assertEqual(
[task["task_id"] for task in second_page],
[self._key(i).decode("utf-8") for i in range(10, 18)],
)
self.assertTrue(state._redis.scan_types)
self.assertEqual(set(state._redis.scan_types), {"HASH"})
def test_get_all_tasks_is_stable_across_scan_reordering_from_restart(self):
"""
issue #1408: Redis 重启/resize 后,不同次 SCAN 看到不同遍历顺序。
同一组 18 个任务,用两种不同的扫描顺序(模拟 rehash 前后)分别
取第一页和第二页 —— 必须拼成完整且不重复的任务集合,顺序也必须
与两次调用保持一致(不依赖具体某一次 SCAN 看到的顺序)。
"""
state = self._build_state([6, 6, 6], cycles=5)
pages = []
for page in range(1, 4):
page_tasks, total = state.get_all_tasks(page=page, page_size=6)
self.assertEqual(total, 18)
pages.append(page_tasks)
all_ids = [task["task_id"] for page_tasks in pages for task in page_tasks]
expected_ids = [self._key(i).decode("utf-8") for i in range(18)]
self.assertEqual(sorted(all_ids), sorted(expected_ids))
self.assertEqual(len(all_ids), len(set(all_ids)), "tasks must not repeat")
self.assertEqual(all_ids, expected_ids)
def test_get_all_tasks_dedupes_keys_returned_twice_in_one_scan(self):
"""
单次 SCAN 周期内,Redis 允许同一个 key 在不同批次中重复出现。
构造一个扫描周期:批次 1 返回 task:000,task:001;批次 2 重复返回
task:001,再带上 task:002。去重后应该只有 3 个任务、total=3,
不能把 task:001 计数两次或在结果里出现两次。
"""
state = RedisState.__new__(RedisState)
key0, key1, key2 = self._key(0), self._key(1), self._key(2)
state._redis = _FakeRedis([[[key0, key1], [key1, key2]]])
tasks, total = state.get_all_tasks(page=1, page_size=10)
self.assertEqual(total, 3)
task_ids = [task["task_id"] for task in tasks]
self.assertEqual(len(task_ids), len(set(task_ids)))
self.assertEqual(
sorted(task_ids),
[key0.decode("utf-8"), key1.decode("utf-8"), key2.decode("utf-8")],
)
def test_get_all_tasks_does_not_skip_or_duplicate_across_two_pagers(self):
"""
复现 issue #1408 给出的最小场景:3 条任务 A,B,C,page_size=2。
第一次独立扫描顺序 A,B,C -> 取第一页;第二次独立扫描顺序 C,A,B
-> 取第二页。旧实现(按批次偏移直接切页,不排序去重)会让第一页
返回 A,B,第二页只返回 B(偏移在新顺序里对应 B),导致 B 重复、
C 整体遗漏。修复后两页基于去重排序后的同一个稳定顺序切片,拼起
来必须正好是 A,B,C,不重不漏。
"""
a, b, c = b"task:A", b"task:B", b"task:C"
state = RedisState.__new__(RedisState)
# 两个不同的扫描周期:第一次顺序 A,B,C,第二次顺序 C,A,B。
state._redis = _FakeRedis([[[a, b, c]], [[c, a, b]]])
first_page, first_total = state.get_all_tasks(page=1, page_size=2)
second_page, second_total = state.get_all_tasks(page=2, page_size=2)
self.assertEqual(first_total, 3)
self.assertEqual(second_total, 3)
combined_ids = [task["task_id"] for task in first_page] + [
task["task_id"] for task in second_page
]
self.assertEqual(
sorted(combined_ids),
sorted([a.decode("utf-8"), b.decode("utf-8"), c.decode("utf-8")]),
)
self.assertEqual(len(combined_ids), len(set(combined_ids)), "no duplicates")
def test_get_all_task_ids_dedupes_and_sorts_in_one_scan(self):
"""
`get_all_task_ids` 供重启恢复一次性取快照用:必须在一次调用里
完成去重,并返回与 SCAN 遍历顺序无关的稳定顺序,这样恢复逻辑才能
只读一次快照、不再重新查询 Redis。
"""
key0, key1, key2 = self._key(0), self._key(1), self._key(2)
state = RedisState.__new__(RedisState)
# 同一次扫描周期内,两个批次重复返回 key1。
state._redis = _FakeRedis([[[key1, key0], [key1, key2]]])
ids = state.get_all_task_ids()
self.assertEqual(
ids,
[key0.decode("utf-8"), key1.decode("utf-8"), key2.decode("utf-8")],
)
@unittest.skipUnless(
os.getenv("MPT_TEST_REDIS_HOST"),
"MPT_TEST_REDIS_HOST not set",
)
def test_real_redis_get_all_tasks_ignores_queue_keys(self):
"""真实 Redis 中的 List 队列不能被任务列表误当作 Hash 读取。"""
state = RedisState(
host=os.environ["MPT_TEST_REDIS_HOST"],
port=int(os.getenv("MPT_TEST_REDIS_PORT", "6379")),
db=int(os.getenv("MPT_TEST_REDIS_DB", "15")),
)
suffix = uuid.uuid4()
task_ids = [f"ci-list-{suffix}-{index}" for index in range(3)]
queue_key = f"ci-queue-{suffix}"
try:
for task_id in task_ids:
state.update_task(
task_id,
state=const.TASK_STATE_COMPLETE,
progress=100,
)
state._redis.rpush(queue_key, *task_ids)
tasks, _ = state.get_all_tasks(page=1, page_size=1000)
returned_ids = {task["task_id"] for task in tasks}
self.assertTrue(set(task_ids).issubset(returned_ids))
self.assertNotIn(queue_key, returned_ids)
finally:
state._redis.delete(queue_key, *task_ids)
def test_patch_task_updates_only_existing_redis_task(self):
state = self._build_state([1])
self.assertTrue(
state.patch_task(
"task:000",
cross_post_state=const.CROSS_POST_STATE_FAILED,
cross_post_error="upload failed",
)
)
task = state.get_task("task:000")
self.assertEqual(task["progress"], 0)
self.assertEqual(task["cross_post_state"], const.CROSS_POST_STATE_FAILED)
self.assertEqual(task["cross_post_error"], "upload failed")
self.assertFalse(state.patch_task("missing", value="ignored"))
@unittest.skipUnless(
os.getenv("MPT_TEST_REDIS_HOST"),
"MPT_TEST_REDIS_HOST not set",
)
def test_real_redis_patch_and_delete_are_atomic(self):
"""真实 Redis 中并发删除和局部更新不能重新创建残缺任务。"""
state = RedisState(
host=os.environ["MPT_TEST_REDIS_HOST"],
port=int(os.getenv("MPT_TEST_REDIS_PORT", "6379")),
db=int(os.getenv("MPT_TEST_REDIS_DB", "15")),
)
for _ in range(50):
task_id = f"ci-atomic-{uuid.uuid4()}"
state.update_task(
task_id,
state=const.TASK_STATE_COMPLETE,
progress=100,
)
barrier = threading.Barrier(2)
def patch_task():
barrier.wait()
state.patch_task(
task_id,
cross_post_state=const.CROSS_POST_STATE_COMPLETE,
)
def delete_task():
barrier.wait()
state.delete_task(task_id)
# Future.result() 会把工作线程异常重新抛到测试线程,避免 Redis
# 命令实际失败但仅打印线程异常、最终仍被误判为测试通过。
with ThreadPoolExecutor(max_workers=2) as executor:
futures = [
executor.submit(patch_task),
executor.submit(delete_task),
]
for future in futures:
future.result(timeout=5)
self.assertIsNone(state.get_task(task_id))
if __name__ == "__main__":
unittest.main()