Refactor reservation preemption handling and logging

- Removed the reservation preempt minimum value from the Runner and GUI components.
- Updated logging mechanism to streamline log message handling and improve readability.
- Introduced a new method for appending log lines in the Runner class.
- Cleaned up related GUI elements and configuration options in web interface.
- Deleted obsolete simulation scripts related to reservation preemption checks.
This commit is contained in:
Your Name committed 2026-01-07 21:24:10 +08:00
1 parent eb96d6869e
commit 93d47a16d6
20 files changed
+786 -1051

No files matched your search

@@ -1,167 +0,0 @@
"""\
模拟检查:预约回退 preempted=True 是否仍会导致 run_once_basic 提前 return。
背景:之前在 `process_reservation_attend_window` 返回 preempted=True 后,
`run_once_basic()` 直接 return,导致锁定期内每轮都重复“预约回退成功”,
但不会进入后续直播间识别/参与逻辑,观感为卡死。
本脚本做两件事:
1) 用 AST 精确定位到包含“预约回退成功:进入回退处理”日志的 if preempted 分支
2) 断言该分支 body 中不包含 `return` 语句(否则就是老 bug 复现)
运行:
.venv/Scripts/python.exe tools/simulate_reservation_preempted_flow.py
"""
from __future__ import annotations
import ast
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
TARGET_FILE = REPO_ROOT / "douyin" / "core" / "douyin_fudai.py"
TARGET_LOG_SNIPPET = "[预约] 预约回退成功:进入回退处理(直接参与标志已移除)"
class _FoundBlock(Exception):
def __init__(self, has_return: bool, lineno: int) -> None:
super().__init__("found")
self.has_return = has_return
self.lineno = lineno
def _node_contains_return(node: ast.AST) -> bool:
"""检查 node 子树中是否存在 return(忽略嵌套函数/类/lambda 内部的 return)。
目的:我们只关心 if preempted 分支本身是否直接 return,
不应把分支里定义的 helper(例如 _write_state 的节流 return)算进去。
"""
class _ReturnFinder(ast.NodeVisitor):
def __init__(self) -> None:
self.found = False
def visit_Return(self, _n: ast.Return) -> None: # noqa: N802
self.found = True
def visit_FunctionDef(self, _n: ast.FunctionDef) -> None: # noqa: N802
# 不进入嵌套函数
return
def visit_AsyncFunctionDef(
self, _n: ast.AsyncFunctionDef
) -> None: # noqa: N802
return
def visit_Lambda(self, _n: ast.Lambda) -> None: # noqa: N802
return
def visit_ClassDef(self, _n: ast.ClassDef) -> None: # noqa: N802
return
finder = _ReturnFinder()
finder.visit(node)
return finder.found
def _node_contains_target_log(node: ast.AST) -> bool:
"""粗略匹配:在该 node 子树中出现目标日志字符串常量。"""
for sub in ast.walk(node):
if isinstance(sub, ast.Constant) and isinstance(sub.value, str):
if TARGET_LOG_SNIPPET in sub.value:
return True
return False
def _check() -> tuple[bool, int]:
src = TARGET_FILE.read_text(encoding="utf-8")
tree = ast.parse(src, filename=str(TARGET_FILE))
parent: dict[ast.AST, ast.AST] = {}
class _ParentBuilder(ast.NodeVisitor):
def generic_visit(self, node: ast.AST) -> None:
for child in ast.iter_child_nodes(node):
parent[child] = node
super().generic_visit(node)
_ParentBuilder().visit(tree)
def _is_self_log_kv_call(n: ast.AST) -> bool:
if not isinstance(n, ast.Call):
return False
f = n.func
return (
isinstance(f, ast.Attribute)
and f.attr == "_log_kv"
and isinstance(f.value, ast.Name)
and f.value.id == "self"
)
def _call_has_target_string(n: ast.Call) -> bool:
for arg in list(n.args) + [kw.value for kw in n.keywords]:
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
if TARGET_LOG_SNIPPET in arg.value:
return True
return False
# 定位 class fudai_analyse -> def run_once_basic
for node in tree.body:
if isinstance(node, ast.ClassDef) and node.name == "fudai_analyse":
for item in node.body:
if isinstance(item, ast.FunctionDef) and item.name == "run_once_basic":
# 先找到目标日志对应的 _log_kv 调用点
target_call: ast.Call | None = None
for sub in ast.walk(item):
if _is_self_log_kv_call(sub) and _call_has_target_string(sub):
target_call = sub
break
if target_call is None:
continue
# 从调用点向上找最近的 enclosing If
cur: ast.AST = target_call
enclosing_if: ast.If | None = None
while cur in parent:
cur = parent[cur]
if isinstance(cur, ast.If):
enclosing_if = cur
break
if enclosing_if is None:
raise RuntimeError(
"Found target log call but could not find enclosing If"
)
has_return = _node_contains_return(enclosing_if)
lineno = getattr(enclosing_if, "lineno", -1)
raise _FoundBlock(has_return=has_return, lineno=lineno)
raise RuntimeError(f"未找到目标分支:{TARGET_LOG_SNIPPET}(文件:{TARGET_FILE})")
def main() -> None:
try:
_check()
# 如果没抛 _FoundBlock,就说明没找到
print("FAIL: could not locate target if(preempted) block")
raise SystemExit(2)
except _FoundBlock as e:
if e.has_return:
print(
"FAIL: early return still exists (can cause reservation back spin) "
f"at {TARGET_FILE}:{e.lineno}"
)
raise SystemExit(1)
print(
"PASS: no early return in preempted=True branch; "
"run_once_basic will continue with follow-up flow "
f"(checked at {TARGET_FILE}:{e.lineno})"
)
if __name__ == "__main__":
main()
@@ -1,138 +0,0 @@
"""\
动态模拟:验证预约回退 preempted=True 后,run_once_basic 不会提前退出。
不连真机/不跑 ADB:
- monkeypatch `douyin.reservation.douyin_reservation_logic.process_reservation_attend_window`
令其返回 True(模拟已触发回退/抢占)。
- 给 analyser 注入一个 FakeOperation,在后续流程的截图阶段抛出哨兵异常。
判定标准:
- 若能捕获到“进入截图阶段”的哨兵异常 => 说明 preempted=True 后仍继续执行到后续流程(PASS)
- 若 run_once_basic 正常 return 或在更早阶段异常退出 => FAIL
运行:
.venv/Scripts/python.exe tools/simulate_reservation_preempted_flow_dynamic.py
"""
from __future__ import annotations
import os
import sys
import time
import traceback
from pathlib import Path
class _ReachedScreenshot(Exception):
pass
class _FakeOperation:
def get_screenshot(self, *_args, **_kwargs):
raise _ReachedScreenshot("reached operation.get_screenshot")
def delay(self, _s: float) -> None:
return
def get_top_package(self, _device_id: str) -> str:
return "com.ss.android.ugc.aweme"
def main() -> None:
# 避免导入底层 OCR 时的初始化开销
os.environ.setdefault("SKIP_OCR_INIT", "1")
# 确保能导入本仓库代码(避免因工作目录不同导致 ModuleNotFoundError)
repo_root = Path(__file__).resolve().parents[1]
if str(repo_root) not in sys.path:
sys.path.insert(0, str(repo_root))
# 1) 导入 analyser
from douyin.core.douyin_fudai import fudai_analyse # noqa: WPS433
# 2) monkeypatch reservation 回退逻辑:强制 preempted=True
from douyin.reservation import douyin_reservation_logic # noqa: WPS433
original_fn = douyin_reservation_logic.process_reservation_attend_window
def _fake_process_reservation_attend_window(
analyser,
reservations,
room_pos,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
**_kwargs,
) -> bool:
# 模拟:已经回退成功并进入锁定期
now = time.time()
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = now + 60.0
if reservation_after_action_pending_ref:
reservation_after_action_pending_ref[0] = True
return True
douyin_reservation_logic.process_reservation_attend_window = (
_fake_process_reservation_attend_window
)
try:
# 3) 构造一个尽量“瘦”的 analyser(避免 __init__ 做太多事)
analyser = fudai_analyse.__new__(fudai_analyse)
# 必要字段:日志、配置、状态
analyser._log_kv = lambda *_a, **_k: None
analyser.operation = _FakeOperation()
analyser.device_id = "FAKE_DEVICE"
analyser._waiting_for_lottery_result = False
analyser._lottery_result_expected_ts = 0.0
# 防止 30 分钟超时分支触发复杂自救
analyser._last_successful_attend_ts = time.time()
analyser._no_attend_timeout_minutes = 30.0
analyser._run_start_ts = time.time()
# 预约相关
analyser.high_value_fudai_enabled = True
analyser.needswitch = True
analyser.room_pos = 7
analyser.reservation_back_swipe_delay = 0.6
analyser.reservations = [
{
"future_ts": time.time() + 120.0,
"prize_value_yuan": 999.0,
"pos_seen": 4,
"content": "",
"room_title": "",
"room_title_raw": "",
}
]
analyser._first_run_once_basic = False
analyser._skip_stage_diagnosis_and_find_fudai = False
# 4) 执行:若 preempted=True 后继续,必然会到截图阶段并触发哨兵异常
try:
analyser.run_once_basic()
except _ReachedScreenshot:
print("PASS: preempted=True did not early-return; reached screenshot stage")
return
print(
"FAIL: run_once_basic returned before reaching screenshot stage "
"(likely early-return or unexpected short-circuit)"
)
raise SystemExit(1)
except Exception as exc:
print(f"FAIL: unexpected exception: {type(exc).__name__}: {exc}")
traceback.print_exc()
raise SystemExit(2)
finally:
# 恢复 monkeypatch
douyin_reservation_logic.process_reservation_attend_window = original_fn
if __name__ == "__main__":
main()