fix(自动还车): 退避上限/巡检口径/加轮传递/0点预判 等 9 处硬化

B1 绝对上限是死代码(P0)
  改前:6 小时上限只写在 _schedule_auto_return_retry 里,而它只被 0 点 Timer 的
  fire 调用一次;第 12 次失败后不再挂 Timer → 上限永远不被评估 → 巡检每 60 秒
  打一轮上游(/bicycle + 最多 3×/record/return + sleep10s + 2 个查询),永不停止。
  改后:上限判断放进 _advance_auto_return_backoff(巡检必经之路),到点只告警一次
  (挡位 99)、清掉 backoff 到点时间、返回 0 = 彻底停手。

B2 巡检路径恒 60 秒,120/300 不可达(P1)
  改前:_advance_auto_return_backoff 调 _auto_return_retry_delay(n) 不传 elapsed,
  而函数里 elapsed=None 恒返回 60。
  改后:传 now-first_fail;30 分钟窗口内 60s,之后 60/120/300s。

B7 first_fail_at 收尾不清(P1,与 B1 联动)
  改前:_clear_auto_return_state 不清 _auto_return_first_fail_at;同一 rental_id 被
  sync 复活后再次失败,setdefault 保留旧时刻 → 立刻判超 6 小时 → 一次告警后停手。
  改后:一并清除。

B6 subscribe 漏在收尾白名单(P1)
  改前:AUTO_RETURN_SOURCES 含 subscribe,但 _finish_active_wechat_rentals 的 SQL
  只有 ('unlock','sync','shared')。用户在微信端还车后本地仍 expired=0,横幅继续
  显示「用车中」、提醒照发。
  改后:白名单补 subscribe。

B9 复活时可能拿到历史行(P2)
  改前:SELECT ... WHERE order_id=? AND user_id=? 无排序无过滤,同 order_id 存在
  历史行+活跃行时会先拿到历史行 → 复活已结束的单 → 撞唯一索引再靠兜底救回。
  改后:ORDER BY expired ASC, id DESC(优先活跃行)。

B4 加轮(rounds_override)不随续租传递(P1,付费承诺)
  改前:_create_renewal_rental 的 INSERT 不含 rounds_override,第 3 轮起
  _planned_rounds 回落到设置值 → 用户点的「+1 轮」被吞掉。
  改后:INSERT 后继承旧行的 rounds_override(老库缺列时忽略)。

B8 0 点 Timer 不预判上游(P2)
  改前:用户已在小程序还车时,仍白打 3 次 /record/return(全 204010)+ sleep 10s,
  并发一封「自动还车失败(紧急)」的吓人邮件 + 一个新 token。
  改后:先问 _upstream_ride_active;已结束就只做本地收尾(_close_rental_locally +
  _clear_auto_return_state + 置位 0),不发还车请求、不发失败邮件。

B13 死 Timer 累积(P3)
  改前:_active_timers[rental_id] 只 append 不清理,重试 11 次后留 12 个死对象。
  改后:登记时过滤掉已结束的 Timer(对没有 is_alive 的假 Timer 容错)。

B14 租约没拿到却占掉节流(P3)
  改前:另一个进程在还这一单时,本地仍写 _recover_last_at,这一单要白等 5 分钟。
  改后:跳过时回滚节流时间戳。

B15 注释与实现漂移
  _recover_throttled 的 docstring 还写「1m→2m→5m→10m 封顶」,与现在的
  60s/120s/300s 不符,已对齐。

测试:新增 tests/test_auto_return_hardening.py 9 例(上限停手、elapsed 档位、
快保不改节奏、first_fail 清理、subscribe 收尾、活跃行优先、rounds_override 继承、
0 点预判已结束 / 仍在骑)。全量 251 pytest + 43 node 全绿。
This commit is contained in:
zzy
2026-11-19 02:04:24 +08:00
parent d570001b03
commit 12c2ce59a1
2 changed files with 413 additions and 12 deletions
+271
View File
@@ -0,0 +1,271 @@
# -*- coding: utf-8 -*-
"""B1/B2/B4/B6/B7/B8/B9 的针对性回归测试。
这些路径原来没有任何测试覆盖 —— 现场故障(到点不还、邮件不发、加轮被吞)
恰好都落在这些空档里。
"""
import os
import sqlite3
import tempfile
import time
import unittest
from pathlib import Path
from unittest.mock import patch
import db
import timer
_RUNTIME_TABLES = None
def _runtime_tables():
global _RUNTIME_TABLES
if _RUNTIME_TABLES is None:
_RUNTIME_TABLES = (
timer._auto_return_retries, timer._auto_return_alert_levels,
timer._auto_return_backoff_until, timer._auto_return_first_fail_at,
timer._recover_last_at, timer._active_timers,
)
return _RUNTIME_TABLES
class _ImmediateTimer:
"""start() 立刻执行 fire():避免 delay=0 的 Timer 带来的竞态。"""
def __init__(self, delay, fn, *a, **kw):
self.delay = delay
self.fn = fn
def start(self):
self.fn()
def cancel(self):
pass
def is_alive(self):
return False
class _Base(unittest.TestCase):
def setUp(self):
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
os.environ["XBCR_DISABLE_LEASES"] = "1"
self.tmp = tempfile.TemporaryDirectory()
self._old_path = db.DB_PATH
db.DB_PATH = Path(self.tmp.name) / "fix.db"
db.init_db()
for table in _runtime_tables():
table.clear()
conn = db.get_db()
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT)")
conn.execute("INSERT OR IGNORE INTO users (id, email) VALUES (7, 'rider@example.test')")
conn.commit()
conn.close()
def tearDown(self):
db.DB_PATH = self._old_path
for table in _runtime_tables():
table.clear()
self.tmp.cleanup()
def add_rental(self, rid, order_id, source="unlock", expired=0,
start="2026-01-01 09:00:00", end="2026-01-01 09:19:00", bike="51287"):
conn = db.get_db()
conn.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, 'rider@example.test', 7, ?, ?, 19, ?, ?)
""", (rid, order_id, bike, start, end, expired, source))
conn.commit()
conn.close()
class BackoffCeilingTests(_Base):
"""B1+B2:退避阶段的绝对上限与档位(原来 6 小时是死代码)。"""
def test_gives_up_after_absolute_ceiling_and_stops_scheduling(self):
rid = 9101
timer._auto_return_retries[rid] = 20
timer._auto_return_first_fail_at[rid] = time.time() - 7 * 3600 # 已失败 7 小时
with patch.object(timer, "_alert_auto_return_exhausted") as alert, \
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
delay = timer._advance_auto_return_backoff(rid, "关锁失败")
self.assertEqual(0, delay, "到绝对上限必须返回 0(停手)")
self.assertNotIn(rid, timer._auto_return_backoff_until,
"停手后不能再留下一次到点时间")
alert.assert_called_once()
self.assertEqual(99, timer._auto_return_alert_levels[rid], "只告警一次(挡位 99)")
with patch.object(timer, "_alert_auto_return_exhausted") as alert2, \
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
timer._advance_auto_return_backoff(rid, "关锁失败")
alert2.assert_not_called()
def test_elapsed_controls_delay_after_dense_phase(self):
rid = 9102
timer._auto_return_retries[rid] = 15
timer._auto_return_first_fail_at[rid] = time.time() - 20 * 60 # 窗口内
with patch.object(timer, "_alert_auto_return_exhausted"), \
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
self.assertEqual(60, timer._advance_auto_return_backoff(rid, "x"))
timer._auto_return_retries[rid] = 20
timer._auto_return_first_fail_at[rid] = time.time() - 40 * 60 # 超过 30 分钟窗口
with patch.object(timer, "_alert_auto_return_exhausted"), \
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
delay = timer._advance_auto_return_backoff(rid, "x")
self.assertIn(delay, (120, 300), f"超过窗口后应拉长,实际 {delay}")
def test_dense_phase_still_no_op(self):
rid = 9103
timer._auto_return_retries[rid] = 3
self.assertEqual(0, timer._advance_auto_return_backoff(rid, "x"))
class ClearStateTests(_Base):
"""B7:收尾要清掉首次失败时刻,否则复活后立刻被判超 6 小时。"""
def test_clear_removes_first_fail_marker(self):
rid = 9201
timer._auto_return_first_fail_at[rid] = time.time() - 8 * 3600
timer._auto_return_retries[rid] = 5
timer._clear_auto_return_state(rid)
self.assertNotIn(rid, timer._auto_return_first_fail_at)
class SubscribeWhitelistTests(_Base):
"""B6:subscribe 单也要能被「微信端已还车」收尾。"""
def test_subscribe_row_is_finished(self):
self.add_rental(9301, "ORD-9301", source="subscribe")
with patch.object(timer, "_bike_pos_from_history", return_value=None):
timer._finish_active_wechat_rentals(7, "上游已无订单")
conn = db.get_db()
row = conn.execute("SELECT expired FROM rentals WHERE id = 9301").fetchone()
conn.close()
self.assertEqual(1, row["expired"], "subscribe 单漏在白名单外会一直显示「用车中」")
class ActiveRowSelectionTests(_Base):
"""B9:同 order_id 有历史行 + 活跃行时,必须拿活跃行。"""
def test_prefers_active_row(self):
self.add_rental(9400, "ORD-9400", expired=1)
self.add_rental(9401, "ORD-9400", expired=0)
active_payload = {"rtn_code": 0, "data": {"nonDealOrder": {
"order_id": "ORD-9400", "status": 2, "code": "51287"}}}
detail_payload = {"rtn_code": 0, "data": {"minutes": 5, "code": "51287"}}
def fake_auth(user_id, method, path, **kw):
return active_payload if path == "/user/info" else detail_payload
with patch.object(timer, "get_user_auth", return_value=("t", "a")), \
patch.object(timer, "request_with_user_auth", side_effect=fake_auth), \
patch.object(timer, "get_user_rental_settings",
return_value={"reminder_enabled": False, "reminder_minutes": [],
"rental_duration_minutes": 19,
"auto_return_enabled": False}), \
patch.object(timer, "start_rental_timer"), \
patch.object(timer, "_bike_pos_from_history", return_value=None):
timer._check_user_order(7)
conn = db.get_db()
rows = conn.execute(
"SELECT id, expired FROM rentals WHERE order_id='ORD-9400' ORDER BY id").fetchall()
conn.close()
state = {r["id"]: r["expired"] for r in rows}
self.assertEqual(1, state[9400], "历史行应保持已结束")
self.assertEqual(0, state[9401], "活跃行应被复活并继续计时")
class RoundOverrideTests(_Base):
"""B4:+1 轮是付费承诺,必须随续租传递。"""
def test_renewal_inherits_rounds_override(self):
self.add_rental(9501, "ORD-9501")
conn = db.get_db()
try:
conn.execute("UPDATE rentals SET rounds_override = 5 WHERE id = 9501")
conn.commit()
except sqlite3.OperationalError:
conn.close()
self.skipTest("当前 schema 没有 rounds_override")
conn.close()
rental = {"id": 9501, "order_id": "ORD-9501", "bike_code": "51287",
"email": "rider@example.test", "source": "unlock",
"renewal_round": 1, "rounds_override": 5,
"end_time": "2026-01-01 09:19:00"}
def fake_auth(user_id, method, path, **kw):
if path == "/record/order":
return {"rtn_code": 0, "data": {"order_id": "ORD-9502"}}
return {"rtn_code": 0, "data": {}}
with patch.object(timer, "_live_bike_position", return_value=(36.5318, 116.7802)), \
patch.object(timer, "request_with_user_auth", side_effect=fake_auth), \
patch.object(timer, "start_rental_timer"):
new_id = timer._create_renewal_rental(
rental, 7, "ORD-9502",
{"rental_duration_minutes": 19, "auto_return_enabled": True,
"reminder_enabled": False, "reminder_minutes": []},
2)
conn = db.get_db()
row = conn.execute("SELECT rounds_override FROM rentals WHERE id = ?",
(new_id,)).fetchone()
conn.close()
self.assertEqual(5, row["rounds_override"],
"续租没继承 rounds_override → 第 3 轮起用户加的轮被吞掉")
class ZeroMinutePrecheckTests(_Base):
"""B8:0 点 Timer 先问上游,别对已还车订单发「自动还车失败(紧急)」。"""
def test_upstream_finished_only_closes_locally(self):
self.add_rental(9601, "ORD-9601")
with patch.object(timer.threading, "Timer", _ImmediateTimer), \
patch.object(timer, "_upstream_ride_active", return_value=False) as precheck, \
patch.object(timer, "auto_return_bike") as auto_return, \
patch.object(timer, "send_rental_notification") as notify, \
patch.object(timer, "_close_rental_locally") as close_local, \
patch.object(timer, "_clear_auto_return_state"), \
patch.object(timer, "_mark_notified"):
timer._schedule_reminder(
rental_id=9601, delay_seconds=0, reminder_type="0",
email="rider@example.test", bike_code="51287", user_id=7,
send_notification=True, gen=None,
)
precheck.assert_called_once()
auto_return.assert_not_called()
close_local.assert_called_once()
notify.assert_not_called()
def test_upstream_still_active_goes_ahead(self):
"""上游确实还在骑时,不能因为预判把自动还车拦掉。"""
self.add_rental(9602, "ORD-9602")
with patch.object(timer.threading, "Timer", _ImmediateTimer), \
patch.object(timer, "_upstream_ride_active", return_value=True), \
patch.object(timer, "auto_return_bike",
return_value={"success": True, "message": "ok"}) as auto_return, \
patch.object(timer, "send_rental_notification"), \
patch.object(timer, "_close_rental_locally") as close_local, \
patch.object(timer, "_clear_auto_return_state"), \
patch.object(timer, "_mark_notified"):
timer._schedule_reminder(
rental_id=9602, delay_seconds=0, reminder_type="0",
email="rider@example.test", bike_code="51287", user_id=7,
send_notification=True, gen=None,
)
auto_return.assert_called_once()
close_local.assert_not_called()
if __name__ == "__main__":
unittest.main()