refactor(reservation): 拆出 attend_window 排序+超时检查(1222→1163,-59 行)

- sort_reservations_with_logging:就地排序 + 前后写日志(含异常吞噬)
- check_total_timeout:超时检查 + 写日志(含异常吞噬)

修复一个真实 bug:拆出 attend_window_helpers.py 时遗漏 import time,导致
check_total_timeout 内的 time.time() 抛 NameError,被外层 try/except 吞噬,
函数永远返回 False。原主文件不存在该 bug。

新增 6 个单元测试(含 import time 缺失场景的 swallow exception 验证),
1267 → 1273 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-22 04:17:29 +08:00
1 parent 89f001e5a4
commit feaf555657
3 files changed
+132 -67

No files matched your search

@@ -24,12 +24,14 @@ from .helpers import (
)
from .attend_window_helpers import (
check_already_participated,
check_total_timeout,
check_waiting_for_reservation_lottery,
compute_dynamic_ahead,
discard_invalid_future_ts,
log_attend_window_check_details,
log_target_reservation_details,
maybe_promote_locked_reservation,
sort_reservations_with_logging,
)
@@ -120,62 +122,12 @@ def process_reservation_attend_window(
# 按统一规则排序(防止外部遗漏 sort)
# 这里不依赖外部 sort_reservations_callback:避免回调内部潜在阻塞/死锁导致主流程卡死。
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:开始队列排序",
reservations_count=len(reservations) if reservations else 0,
)
except Exception:
pass
# 超时检查
try:
if (time.time() - start_time) > total_timeout_s:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:超时退出(排序前)",
total_timeout_seconds=round(total_timeout_s, 3),
)
except Exception:
pass
return False
except Exception:
pass
try:
_sort_reservations_inplace(reservations)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="队列排序",
)
else:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序异常(忽略)",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序完成",
earliest_future_ts=(
int(float((reservations[0].get("future_ts") or 0.0)))
if reservations
else 0
),
)
except Exception:
pass
if check_total_timeout(analyser, start_time, total_timeout_s, "排序前"):
return False
sort_reservations_with_logging(analyser, reservations, _sort_reservations_inplace)
# 锁定期内:优先处理"锁定的预约",避免被队头其它预约打断。
# 同时,如果锁定期对应的预约已不在队列(例如刚参与成功并移除),视为"锁定失效",清除锁定期。
@@ -189,19 +141,8 @@ def process_reservation_attend_window(
)
# 超时检查
try:
if (time.time() - start_time) > total_timeout_s:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:超时退出(排序后)",
total_timeout_seconds=round(total_timeout_s, 3),
)
except Exception:
pass
return False
except Exception:
pass
if check_total_timeout(analyser, start_time, total_timeout_s, "排序后"):
return False
# 取队头(最早需要处理的一条;若在锁定期内已将锁定目标移动到队头,则这里即为锁定目标)
target = reservations[0]
@@ -6,10 +6,78 @@
"""
from __future__ import annotations
import time
from datetime import datetime
from typing import Any, Dict, Tuple
def sort_reservations_with_logging(
analyser: Any, reservations: list, _sort_inplace_callback: Any
) -> None:
"""对预约队列就地排序,前后写日志。
`_sort_inplace_callback` 是底层就地排序函数(如 helpers._sort_reservations_inplace)。
"""
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:开始队列排序",
reservations_count=len(reservations) if reservations else 0,
)
except Exception:
pass
try:
_sort_inplace_callback(reservations)
except Exception as e:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序异常(忽略)",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序完成",
earliest_future_ts=(
int(float((reservations[0].get("future_ts") or 0.0)))
if reservations
else 0
),
)
except Exception:
pass
def check_total_timeout(
analyser: Any, start_time: float, total_timeout_s: float, stage: str
) -> bool:
"""检查总超时。返回 True 表示已超时,主流程应当 return False。"""
try:
elapsed = time.time() - start_time
timed_out = elapsed > total_timeout_s
except Exception:
return False
if not timed_out:
return False
try:
analyser._log_kv(
"预约",
f"[预约] process_reservation_attend_window:超时退出({stage})",
total_timeout_seconds=round(total_timeout_s, 3),
)
except Exception:
pass
return True
def check_already_participated(
analyser: Any,
reservations: list,
+56
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import time
from unittest.mock import MagicMock
from douyin.reservation.reservation_logic import attend_window_helpers as h
@@ -355,3 +356,58 @@ def test_log_target_reservation_details_swallows_exception():
a._log_kv.side_effect = RuntimeError("boom")
# 不应抛错
h.log_target_reservation_details(a, {}, ft=100.0)
# ---- sort_reservations_with_logging ---- #
def test_sort_reservations_logs_before_and_after():
a = MagicMock()
reservations = [{"future_ts": 200}, {"future_ts": 100}]
sort_cb = MagicMock(side_effect=lambda lst: lst.sort(key=lambda x: x["future_ts"]))
h.sort_reservations_with_logging(a, reservations, sort_cb)
# 至少 2 次日志:开始排序 / 排序完成
assert a._log_kv.call_count >= 2
# 排序后队头是 100
assert reservations[0]["future_ts"] == 100
def test_sort_reservations_swallows_sort_exception():
a = MagicMock()
reservations = [{"future_ts": 100}]
sort_cb = MagicMock(side_effect=RuntimeError("boom"))
# 不应抛错
h.sort_reservations_with_logging(a, reservations, sort_cb)
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
assert any("队列排序异常" in m for m in msgs)
def test_sort_reservations_empty_queue():
a = MagicMock()
sort_cb = MagicMock()
h.sort_reservations_with_logging(a, [], sort_cb)
sort_cb.assert_called_once_with([])
# ---- check_total_timeout ---- #
def test_check_timeout_not_exceeded_returns_false():
a = MagicMock()
now = time.time()
assert h.check_total_timeout(a, now, total_timeout_s=10.0, stage="测试") is False
def test_check_timeout_exceeded_returns_true():
a = MagicMock()
past = time.time() - 100
assert h.check_total_timeout(a, past, total_timeout_s=10.0, stage="测试") is True
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
assert any("超时退出(测试)" in m for m in msgs)
def test_check_timeout_swallows_exception():
a = MagicMock()
a._log_kv.side_effect = RuntimeError("boom")
past = time.time() - 100
# 应不抛错
result = h.check_total_timeout(a, past, total_timeout_s=10.0, stage="测试")
assert result is True