From feaf5556575374fda0cb33e73bfd1b1347ea0882 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 22 May 2026 04:17:29 +0800 Subject: [PATCH] =?UTF-8?q?refactor(reservation):=20=E6=8B=86=E5=87=BA=20a?= =?UTF-8?q?ttend=5Fwindow=20=E6=8E=92=E5=BA=8F+=E8=B6=85=E6=97=B6=E6=A3=80?= =?UTF-8?q?=E6=9F=A5=EF=BC=881222=E2=86=921163=EF=BC=8C-59=20=E8=A1=8C?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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) --- .../reservation_logic/attend_window.py | 75 ++----------------- .../attend_window_helpers.py | 68 +++++++++++++++++ tests/test_attend_window_helpers.py | 56 ++++++++++++++ 3 files changed, 132 insertions(+), 67 deletions(-) diff --git a/douyin/reservation/reservation_logic/attend_window.py b/douyin/reservation/reservation_logic/attend_window.py index 1d6c236..a70bde2 100644 --- a/douyin/reservation/reservation_logic/attend_window.py +++ b/douyin/reservation/reservation_logic/attend_window.py @@ -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] diff --git a/douyin/reservation/reservation_logic/attend_window_helpers.py b/douyin/reservation/reservation_logic/attend_window_helpers.py index 2d3db7e..b8b799d 100644 --- a/douyin/reservation/reservation_logic/attend_window_helpers.py +++ b/douyin/reservation/reservation_logic/attend_window_helpers.py @@ -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, diff --git a/tests/test_attend_window_helpers.py b/tests/test_attend_window_helpers.py index b684447..e30a390 100644 --- a/tests/test_attend_window_helpers.py +++ b/tests/test_attend_window_helpers.py @@ -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