feat: Enhance logging and parameter tracking capabilities

- Refactor `gui_core.py` to improve code readability and maintainability by adding line breaks for long statements.
- Introduce `inspect_lines.py` script for inspecting specific line ranges in files.
- Add `generate_param_locations.py` to scan the repository and generate a report of function definitions, argparse parameters, and tracking calls.
- Implement `param_usage_tool.py` for analyzing `param_usage.json` records and scanning code for tracking calls.
- Create `simulate_reservation_preempted_flow.py` and `simulate_reservation_preempted_flow_dynamic.py` to validate behavior of reservation logic under specific conditions.
- Add global parameter tracking feature in `run_cli.py` to enable detailed usage tracing.
This commit is contained in:
Your Name committed 2026-01-03 19:12:58 +08:00
1 parent 68c8ccea66
commit 95b4517bdd
23 files changed
+1560 -849

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
"""扫描仓库并生成参数位置报告。
输出文件:`state/param_locations.json`,包含:
- functions: 列出所有函数定义及其参数
- argparse: 列出所有 argparse 的 add_argument 参数名
- track_param_calls: 列出所有 `track_param(...)` 调用位置与第一个参数(如果为字符串字面量)
- track_call_calls: 列出所有 `track_call` 出现位置
用法:
python tools/generate_param_locations.py
"""
from __future__ import annotations
import ast
import json
import os
import re
from typing import Dict, List, Any
ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
OUT_PATH = os.path.join(ROOT, "state", "param_locations.json")
def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]:
res = {"functions": [], "argparse": [], "track_param_calls": [], "track_call_calls": []}
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
src = f.read()
except Exception:
return res
try:
tree = ast.parse(src, filename=path)
except Exception:
# fallback to regex scanning
for i, line in enumerate(src.splitlines(), 1):
if "track_param(" in line:
res["track_param_calls"].append({"file": path, "line": i, "text": line.strip()})
if "track_call(" in line or "@track_call" in line:
res["track_call_calls"].append({"file": path, "line": i, "text": line.strip()})
if "add_argument(" in line:
# try extract string args
for m in re.finditer(r"([\'\"]--?[\w-]+[\'\"])", line):
res["argparse"].append({"file": path, "line": i, "arg": m.group(1).strip("'\"")})
return res
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
params = []
for a in node.args.args:
params.append(a.arg)
# include varargs/kw
if node.args.vararg:
params.append("*" + node.args.vararg.arg)
if node.args.kwarg:
params.append("**" + node.args.kwarg.arg)
res["functions"].append({"file": path, "line": node.lineno, "name": node.name, "params": params})
if isinstance(node, ast.Call):
# add_argument
try:
func = node.func
func_name = None
if isinstance(func, ast.Attribute):
func_name = func.attr
elif isinstance(func, ast.Name):
func_name = func.id
if func_name == "add_argument":
# extract string literals from args
for arg in node.args:
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
res["argparse"].append({"file": path, "line": node.lineno, "arg": arg.value})
# track_param calls
if (isinstance(func, ast.Name) and func.id == "track_param") or (
isinstance(func, ast.Attribute) and func.attr == "track_param"
):
first = None
if node.args:
a0 = node.args[0]
if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
first = a0.value
res["track_param_calls"].append({"file": path, "line": node.lineno, "param_name": first})
if (isinstance(func, ast.Name) and func.id == "track_call") or (
isinstance(func, ast.Attribute) and func.attr == "track_call"
):
res["track_call_calls"].append({"file": path, "line": node.lineno})
except Exception:
pass
return res
def main() -> int:
out: Dict[str, List[Any]] = {"functions": [], "argparse": [], "track_param_calls": [], "track_call_calls": []}
for dirpath, dirs, files in os.walk(ROOT):
# skip virtual envs and git
if ".venv" in dirpath or ".git" in dirpath:
continue
for fn in files:
if not fn.endswith(".py"):
continue
path = os.path.join(dirpath, fn)
parts = scan_py_file(path)
for k in out:
out[k].extend(parts.get(k, []))
os.makedirs(os.path.dirname(OUT_PATH), exist_ok=True)
with open(OUT_PATH, "w", encoding="utf-8") as f:
json.dump({"generated_at": __import__("time").time(), "report": out}, f, ensure_ascii=False, indent=2)
print("written:", OUT_PATH)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+149
View File
@@ -0,0 +1,149 @@
"""命令行工具:查看与分析 `state/param_usage.json` 记录,或静态扫描代码中的跟踪调用。
用法示例:
python tools/param_usage_tool.py show --limit 200
python tools/param_usage_tool.py scan --pattern track_param
python tools/param_usage_tool.py tail
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from collections import defaultdict
from typing import Dict, List
ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
STATE_PATH = os.path.join(ROOT, "state", "param_usage.json")
def read_entries(path: str) -> List[Dict]:
if not os.path.exists(path):
return []
out = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
out.append(json.loads(line))
except Exception:
continue
return out
def cmd_show(args: argparse.Namespace) -> int:
entries = read_entries(STATE_PATH)
if not entries:
print("no entries found: {}".format(STATE_PATH))
return 1
if args.limit:
entries = entries[-args.limit :]
by_param = defaultdict(list)
calls = []
for e in entries:
t = e.get("type")
if t == "param_access":
by_param[e.get("param")].append(e)
else:
calls.append(e)
print("Summary:")
print(" param_access entries: {}".format(sum(len(v) for v in by_param.values())))
print(" call entries: {}".format(len(calls)))
print("")
if args.param:
items = by_param.get(args.param)
if not items:
print(f"no records for param: {args.param}")
return 0
for i in items:
print(json.dumps(i, ensure_ascii=False))
return 0
# show top params
top = sorted(by_param.items(), key=lambda kv: -len(kv[1]))[: args.top]
for name, lst in top:
first = lst[0]
print(f"{name}: count={len(lst)} first_at={first.get('caller_file')}:{first.get('caller_line')}")
return 0
def cmd_tail(args: argparse.Namespace) -> int:
print("tailing {} (press Ctrl-C to stop)".format(STATE_PATH))
try:
with open(STATE_PATH, "r", encoding="utf-8") as f:
# seek to end
f.seek(0, os.SEEK_END)
while True:
line = f.readline()
if not line:
time.sleep(0.5)
continue
print(line.rstrip())
except KeyboardInterrupt:
return 0
except FileNotFoundError:
print("file not found: {}".format(STATE_PATH))
return 1
def cmd_scan(args: argparse.Namespace) -> int:
root = os.path.abspath(args.root or ROOT)
matches = []
for dirpath, dirs, files in os.walk(root):
# skip virtual envs and .git
if ".venv" in dirpath or ".git" in dirpath:
continue
for fn in files:
if not fn.endswith((".py", ".md", ".txt")):
continue
path = os.path.join(dirpath, fn)
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for i, line in enumerate(f, 1):
if args.pattern in line:
matches.append((path, i, line.strip()))
except Exception:
continue
for p, lno, text in matches:
print(f"{p}:{lno}: {text}")
print(f"found {len(matches)} matches for '{args.pattern}'")
return 0
def main(argv: List[str]) -> int:
p = argparse.ArgumentParser(description="Param usage viewer tool")
sp = p.add_subparsers(dest="cmd")
s_show = sp.add_parser("show")
s_show.add_argument("--limit", type=int, default=200)
s_show.add_argument("--top", type=int, default=20)
s_show.add_argument("--param", type=str, help="show specific param records")
s_show.set_defaults(func=cmd_show)
s_tail = sp.add_parser("tail")
s_tail.set_defaults(func=cmd_tail)
s_scan = sp.add_parser("scan")
s_scan.add_argument("pattern", help="substring to search for")
s_scan.add_argument("--root", help="root to scan")
s_scan.set_defaults(func=cmd_scan)
args = p.parse_args(argv)
if not args.cmd:
p.print_help()
return 1
return args.func(args)
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,167 @@
"""\
模拟检查:预约回退 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()
@@ -0,0 +1,140 @@
"""\
动态模拟:验证预约回退 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()