From 99c3fb1a22759bd5e52112a7ea807753c0316d4c Mon Sep 17 00:00:00 2001 From: Nixevol Date: Tue, 17 Nov 2026 12:23:39 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=B9=B3=E5=8F=B0=E4=B8=A2=E6=8E=89?= =?UTF-8?q?=E8=BF=87=E5=BF=AB=E5=BF=83=E8=B7=B3=E6=97=B6=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=8A=8A=E8=AF=BE=E7=A8=8B=E5=88=A4=E6=88=90=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/euniv/autostudy.py | 126 ++++++++++++++++++++++++++++---- backend/tests/test_autostudy.py | 103 ++++++++++++++++++++++++++ 2 files changed, 213 insertions(+), 16 deletions(-) diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index 0827667..b09ea70 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -261,12 +261,24 @@ def _progress_of(payload: dict) -> float: class _Stall: - """累计申报满 5 分钟,百分比和已获得学时都没动,才放弃。空的成功响应不算失败。""" + """平台入账后,申报满 5 分钟仍无进度才放弃。没入账的心跳按真实时间等满 5 分钟才放弃。""" def __init__(self) -> None: self.declared = 0 self.baseline: float | None = None self.earned: float | None = None + self.quiet_since: float | None = None + self.paced = False + + def note_landed(self) -> None: + self.quiet_since = None + self.paced = False + + def quiet(self, now: float | None = None) -> bool: + current = time.time() if now is None else now + if self.quiet_since is None: + self.quiet_since = current + return current - self.quiet_since >= 300 def stuck(self, progress: float, sent: int, earned: float | None = None) -> bool: if self.baseline is None: @@ -285,6 +297,55 @@ class _Stall: return self.declared >= 300 and not moved +def _beat_landed( + before: float, + after: float, + before_earned: float | None, + after_earned: float | None, + result: object, + *, + video: bool, +) -> bool: + """百分比或已获得学时增加,算入账。视频只有带回 studySchedule 才算平台收下了这次心跳。""" + if after > before + 0.01: + return True + if after_earned is not None and (before_earned is None or after_earned > before_earned + 0.01): + return True + if not video or not isinstance(result, dict): + return False + schedule = result.get("studySchedule") + return schedule not in (None, "") + + +def _pace_wait(interval: int, step: int, landed: bool) -> int: + """没入账时至少等到平台的一段时长,下一次心跳才有机会被记上。""" + chosen = 1 if interval <= 0 else int(interval) + if landed or step <= 0: + return chosen + return max(chosen, int(step)) + + +def _pace_after( + stall: _Stall, + before: float, + after: float, + before_earned: float | None, + after_earned: float | None, + result: object, + *, + video: bool, + step: int, + interval: int, + now: float | None = None, +) -> tuple[bool, bool, int]: + """返回 (是否入账, 是否放弃, 下一次等待秒)。""" + landed = _beat_landed(before, after, before_earned, after_earned, result, video=video) + if landed: + stall.note_landed() + return True, stall.stuck(after, step, after_earned), _pace_wait(interval, step, True) + return False, stall.quiet(now), _pace_wait(interval, step, False) + + def _completed(payload: dict) -> bool: if not isinstance(payload, dict): return False @@ -1207,12 +1268,16 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, interval: int, stop: asyncio.Event, hours: HoursWatcher, worker: WorkerView | None = None, study_time: int | None = None, - snapshot: dict | None = None) -> None: + snapshot: dict | None = None, + video_cap: int | None = None) -> None: step = int(study_time if study_time is not None else (interval if interval > 0 else 30)) if step <= 0: step = 30 view = 0 - cap = int(getattr(session, "_video_cap", 0) or 0) + if video_cap is None: + cap = int(getattr(session, "_video_cap", 0) or 0) + else: + cap = max(0, int(video_cap)) if worker is not None and worker.total <= 0 and cap > 0: start_at = _whole((snapshot or {}).get("viewSchedule"), 0) worker.total = _planned_beats(cap, start_at, step) @@ -1247,11 +1312,12 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, await hours.refresh() return started = True + before = schedule + before_earned = _earned_minutes(progress) view = _whole(progress.get("viewSchedule"), view) view = max(0, view + step + random.randint(-1, 1)) - limit = int(getattr(session, "_video_cap", 0) or 0) - if limit > 0: - view = min(view, limit) + if cap > 0: + view = min(view, cap) page_rhythm = interval > 0 and interval == step if page_rhythm and await _heartbeat_wait(worker, interval, stop, hours, schedule): return @@ -1267,14 +1333,24 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, new_schedule = result.get("studySchedule") if isinstance(result, dict) else None if new_schedule is not None: schedule = max(schedule, _progress_of({"studySchedule": new_schedule})) - _beat(worker, schedule, ok=True) + landed, give_up, pause = _pace_after( + stall, before, schedule, before_earned, _earned_minutes(fresh), result, + video=True, step=step, interval=interval, + ) + if landed: + _beat(worker, schedule, ok=True) + else: + _touch(worker, progress=schedule, ok=True) + if not stall.paced: + stall.paced = True + log.info("平台没有记下这次视频心跳,改为隔 %s 秒再发", pause) if schedule >= 100 or _completed(fresh): await hours.refresh() return - if stall.stuck(schedule, step, _earned_minutes(fresh)): + if give_up: raise RuntimeError("进度长时间没有变化") if not page_rhythm: - if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule): + if await _heartbeat_wait(worker, pause, stop, hours, schedule): return @@ -1306,6 +1382,8 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, await hours.refresh() return started = True + before = schedule + before_earned = _earned_minutes(progress) view = int(progress.get("viewSchedule") or 1) page_rhythm = interval > 0 and interval == step if page_rhythm and await _heartbeat_wait(worker, interval, stop, hours, schedule): @@ -1319,14 +1397,24 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, raise fresh = await session.update_progress(kid, pkg_id) schedule = _progress_of(fresh) - _beat(worker, schedule, ok=True) + landed, give_up, pause = _pace_after( + stall, before, schedule, before_earned, _earned_minutes(fresh), None, + video=False, step=step, interval=interval, + ) + if landed: + _beat(worker, schedule, ok=True) + else: + _touch(worker, progress=schedule, ok=True) + if not stall.paced: + stall.paced = True + log.info("平台没有记下这次文档心跳,改为隔 %s 秒再发", pause) if _completed(fresh): await hours.refresh() return - if stall.stuck(schedule, step, _earned_minutes(fresh)): + if give_up: raise RuntimeError("进度长时间没有变化") if not page_rhythm: - if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule): + if await _heartbeat_wait(worker, pause, stop, hours, schedule): return @@ -1473,8 +1561,12 @@ async def _study_package(session: StudySession, kid: str, intervals: dict, params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type)) wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params) if ch_type == "video": - session._video_cap = _whole(params.get("standardStudyHours"), 0) - await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time) + cap = _whole(params.get("standardStudyHours"), 0) + session._video_cap = cap + await _study_video( + session, ch_kid, kid, wait, stop, hours, worker, + study_time=study_time, video_cap=cap, + ) else: session._video_cap = 0 await _study_document( @@ -1944,8 +2036,10 @@ class AutoStudyWorker: wait, study_time, page_size = _interval_plan(ctype, intervals, auto_mode, params) session._single_limit = str(params.get("isSingle") or "") == "1" if ctype == "video": - session._video_cap = _whole(params.get("standardStudyHours"), 0) + video_cap = _whole(params.get("standardStudyHours"), 0) + session._video_cap = video_cap else: + video_cap = 0 session._video_cap = 0 if ctype == "document" and _uses_new_timer(params) and auto_mode: page_gap = _whole(params.get("submitProTimes"), 30) @@ -1965,7 +2059,7 @@ class AutoStudyWorker: if ctype == "video": await _study_video( session, kid, "", wait, self._async_stop, hours, worker, - study_time=study_time, snapshot=progress, + study_time=study_time, snapshot=progress, video_cap=video_cap, ) elif ctype == "document": await _study_document( diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index 8ea2935..3d87236 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -25,6 +25,7 @@ from euniv.autostudy import ( _set_user_status, _set_worker_status, _Stall, + _pace_after, _study_document, _study_video, autostudy_status, @@ -139,6 +140,108 @@ def test_stall_gives_up_after_five_minutes_without_progress() -> None: assert credited.stuck(10.41, 30, 5) is False +def test_rejected_heartbeat_waits_for_platform_chunk_instead_of_failing() -> None: + stall = _Stall() + for offset in range(12): + landed, give_up, pause = _pace_after( + stall, 16.67, 16.67, 2, 2, {}, + video=True, step=30, interval=1, now=1000 + offset, + ) + assert landed is False + assert give_up is False + assert pause == 30 + landed, give_up, pause = _pace_after( + stall, 16.67, 25, 2, 3, {"studySchedule": 25}, + video=True, step=30, interval=1, now=1400, + ) + assert landed is True + assert give_up is False + assert pause == 1 + landed, give_up, pause = _pace_after( + stall, 25, 25, 3, 3, {}, + video=True, step=30, interval=1, now=1401, + ) + assert give_up is False + assert pause == 30 + assert stall.quiet(1701) is True + + +def test_accepted_but_flat_heartbeat_still_gives_up() -> None: + stall = _Stall() + for _ in range(9): + landed, give_up, pause = _pace_after( + stall, 10, 10, 1, 1, {"studySchedule": 10}, + video=True, step=30, interval=1, now=1000, + ) + assert landed is True + assert give_up is False + assert pause == 1 + landed, give_up, _pause = _pace_after( + stall, 10, 10, 1, 1, {"studySchedule": 10}, + video=True, step=30, interval=1, now=1000, + ) + assert landed is True + assert give_up is True + + +def test_fast_video_survives_a_burst_of_empty_heartbeats(monkeypatch) -> None: + monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None) + waits: list[int] = [] + + async def capture_wait(_worker, interval, _stop, _hours, _progress) -> bool: + waits.append(interval) + return False + + monkeypatch.setattr("euniv.autostudy._heartbeat_wait", capture_wait) + + class Session: + def __init__(self) -> None: + self.submits = 0 + + async def update_progress(self, _kid: str, _pkg: str) -> dict: + if self.submits >= 10: + return { + "studyschedule": 100, + "status": "Completed", + "actualstudyhours": 3, + "viewSchedule": 300, + } + return { + "studyschedule": 16.67, + "status": "Studying", + "actualstudyhours": 2, + "viewSchedule": 89, + } + + async def submit_video_heartbeat(self, _kid: str, _pkg: str, _study_time: int, _view: int) -> dict: + self.submits += 1 + if self.submits >= 10: + return {"studySchedule": 100} + return {} + + async def month_hours_text(self) -> str: + return "10" + + async def main() -> None: + session = Session() + watcher = HoursWatcher(session, "u-burst", 600, asyncio.Event()) + await _study_video( + session, "kid", "", 1, asyncio.Event(), watcher, + study_time=30, + snapshot={ + "studyschedule": 16.67, + "status": "Studying", + "actualstudyhours": 2, + "viewSchedule": 89, + }, + video_cap=720, + ) + assert session.submits == 10 + assert waits == [30] * 9 + + asyncio.run(main()) + + def test_jitter_never_sends_early() -> None: assert _jitter(0) == 1 assert _jitter(-1) == 1