diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index eef71c6..de57420 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -210,6 +210,23 @@ def _progress_of(payload: dict) -> float: return 0.0 +class _Stall: + """累计申报满 5 分钟仍无进度时放弃,避免短间隔把一门课打成死循环。""" + + def __init__(self) -> None: + self.declared = 0 + self.baseline: float | None = None + + def stuck(self, progress: float, sent: int) -> bool: + if self.baseline is None: + self.baseline = progress + elif progress > self.baseline + 0.01: + self.baseline = progress + self.declared = 0 + self.declared += max(0, sent) + return self.declared >= 300 and progress <= self.baseline + 0.01 + + def _completed(payload: dict) -> bool: if not isinstance(payload, dict): return False @@ -912,6 +929,7 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, step = 30 view = 0 started = False + stall = _Stall() while not _halted(stop, hours): try: progress = await session.update_progress(kid, pkg_id) @@ -944,6 +962,8 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, if schedule >= 100: await hours.refresh() return + if stall.stuck(schedule, step): + raise RuntimeError("进度长时间没有变化") if not page_rhythm: if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule): return @@ -957,6 +977,7 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, if step <= 0: step = 120 started = False + stall = _Stall() while not _halted(stop, hours): try: progress = await session.update_progress(kid, pkg_id) @@ -987,6 +1008,8 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, if _completed(progress): await hours.refresh() return + if stall.stuck(schedule, step): + raise RuntimeError("进度长时间没有变化") if not page_rhythm: if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule): return diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index 86ca765..ef2d45d 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -23,6 +23,7 @@ from euniv.autostudy import ( _play_path, _set_user_status, _set_worker_status, + _Stall, _study_document, _study_video, autostudy_status, @@ -121,6 +122,18 @@ def test_wait_stop_timeout_and_event() -> None: asyncio.run(main()) +def test_stall_gives_up_after_five_minutes_without_progress() -> None: + stall = _Stall() + assert stall.stuck(10, 120) is False + assert stall.stuck(10, 120) is False + assert stall.stuck(10, 120) is True + moved = _Stall() + assert moved.stuck(10, 120) is False + assert moved.stuck(40, 200) is False + assert moved.stuck(40, 99) is False + assert moved.stuck(40, 1) is True + + def test_jitter_never_sends_early() -> None: assert _jitter(0) == 1 assert _jitter(-1) == 1