From 589a4ce39aee143ce0b58bd8781a76028eea8d74 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Mon, 27 Jul 2026 05:09:11 +0800 Subject: [PATCH] fix: settle windows from a durable cursor, align idempotency keys and clocks _agenda_closed_windows scanned a fixed -3..+1 day range. Past three days of downtime the missed windows were never settled and left no trace -- "zero snapshots" and "not due yet" look identical from the data, which is why this sat in the backlog for four rounds. It now scans forward from a persisted agenda_last_settled cursor, falling back to the old three days when the cursor is absent. Catch-up is capped at 30 days and says so in the log rather than truncating silently. The cursor advances only after both the snapshot and the reconciliation are written, and never moves backwards. Two long-deferred contract deviations went with it. reconciliation_id already carries its own "reconciliation:" prefix and got another one on top; window snapshots used the internal snapshot id as a business key. Both now go through _bot_personal_window_key and match the formats the frozen contract recommends. Records already stored keep their old keys -- settlements and snapshots are terminal per-window writes, so there is nothing left to update. The outbox called datetime.now() directly while window attribution used the plugin's _environment_now. The now parameter had been there all along and no caller passed it, which is more hidden than not having it at all. All eight call sites now pass the plugin clock; the test asserts a 2031 timestamp so a system-clock regression cannot pass. Companion suite 231 passed, joint E2E 135/135. VM restarted clean. Co-Authored-By: Claude Opus 5 --- agenda_runtime.py | 57 ++++++++++++- docs/运维陪伴错题本.md | 30 +++++++ memory_companion_adapter.py | 57 ++++++++++--- tests/test_agenda_settle_cursor.py | 111 +++++++++++++++++++++++++ tests/test_p3_key_and_clock.py | 125 +++++++++++++++++++++++++++++ 5 files changed, 367 insertions(+), 13 deletions(-) create mode 100644 tests/test_agenda_settle_cursor.py create mode 100644 tests/test_p3_key_and_clock.py diff --git a/agenda_runtime.py b/agenda_runtime.py index 4744171..9e1807c 100644 --- a/agenda_runtime.py +++ b/agenda_runtime.py @@ -7,6 +7,8 @@ from copy import deepcopy from datetime import datetime, timedelta from typing import Any +from astrbot.api import logger + try: from .activity_capture import ActivityCapture from .agenda_contracts import interval_overlaps_window, migrate_store, normalize_observed_activity, normalize_window_snapshot, window_bounds, window_for_datetime @@ -21,6 +23,11 @@ except ImportError: from calendar_system import plan_item_to_event +# 停机再长也不会无限往回补算;超出这个跨度的窗口会明确告警后放弃, +# 而不是像原来那样默默消失在固定的 3 天扫描窗外。 +AGENDA_SETTLE_MAX_CATCHUP_DAYS = 30 + + class AgendaRuntimeMixin: def _agenda_prepare_store(self) -> None: data, changed = migrate_store(self.data) @@ -280,6 +287,31 @@ class AgendaRuntimeMixin: def _agenda_snapshot_id(self, date_key: str, window: str) -> str: return f"snapshot-{date_key}-{window}" + def _agenda_settle_cursor_date(self) -> str: + """上次结算推进到的日期。空串表示还没有游标(首次运行或旧数据)。""" + value = self.data.get("agenda_last_settled") if isinstance(self.data, dict) else None + if isinstance(value, dict): + value = value.get("date") + text = str(value or "").strip()[:10] + try: + datetime.strptime(text, "%Y-%m-%d") + except ValueError: + return "" + return text + + def _agenda_note_settled(self, date_key: str, window: str) -> None: + """把游标推到已结算的这个窗口。只前进不后退。""" + text = str(date_key or "").strip()[:10] + if not text: + return + current = self._agenda_settle_cursor_date() + if current and text < current: + return + self.data["agenda_last_settled"] = {"date": text, "window": str(window or "")} + saver = getattr(self, "_schedule_data_save", None) + if callable(saver): + saver(delay=0.0) + def _agenda_closed_windows(self, now: datetime) -> list[tuple[str, str]]: timezone_name = self._agenda_timezone_name() local_now = now @@ -287,10 +319,27 @@ class AgendaRuntimeMixin: local_now = local_now.replace(tzinfo=window_bounds(now.date(), "早晨", timezone_name=timezone_name)[0].tzinfo) local_now = local_now.astimezone(window_bounds(local_now.date(), "早晨", timezone_name=timezone_name)[0].tzinfo) existing_ids = {str(item.get("snapshot_id")) for item in self._agenda_snapshots_store() if isinstance(item, dict)} + # 这里原本固定扫 -3..+1 天:停机超过 3 天,中间的窗口永远不会被补算, + # 而且不留任何痕迹。改成从上次结算游标往前扫,游标缺失时退回原来的 3 天。 + cursor = self._agenda_settle_cursor_date() + today = local_now.date() + start = today - timedelta(days=3) + if cursor: + start = datetime.strptime(cursor, "%Y-%m-%d").date() + earliest = today - timedelta(days=AGENDA_SETTLE_MAX_CATCHUP_DAYS) + if start < earliest: + logger.warning( + "[PrivateCompanion] 窗口结算落后至 %s,超出 %s 天补算上限,%s 之前的窗口不再补算", + start.isoformat(), + AGENDA_SETTLE_MAX_CATCHUP_DAYS, + earliest.isoformat(), + ) + start = earliest candidates: list[tuple[str, str]] = [] - for offset in range(-3, 2): - target = local_now.date() + timedelta(days=offset) - for name, _, _ in (("深夜", 0, 0), ("早晨", 0, 0), ("下午", 0, 0), ("晚上", 0, 0)): + span = (today - start).days + 2 + for offset in range(span): + target = start + timedelta(days=offset) + for name in ("深夜", "早晨", "下午", "晚上"): _, end = window_bounds(target, name, timezone_name=timezone_name) snapshot_id = self._agenda_snapshot_id(target.isoformat(), name) if end <= local_now and snapshot_id not in existing_ids: @@ -317,6 +366,8 @@ class AgendaRuntimeMixin: await reconciliation_recorder(reconciliation) except Exception: pass + # 游标只在这一整套(快照 + 结算)都走完之后才推进 + self._agenda_note_settled(date_key, window) sleep_text = str(getattr(self, "daily_diary_time", "23:10") or "23:10") try: hour_text, minute_text = sleep_text.split(":", 1) diff --git a/docs/运维陪伴错题本.md b/docs/运维陪伴错题本.md index f00ab8c..e235f60 100644 --- a/docs/运维陪伴错题本.md +++ b/docs/运维陪伴错题本.md @@ -561,3 +561,33 @@ docs\运维陪伴错题本.md - 修复或规避:新增 `_daily_plan_can_upgrade_from_fallback`,当天的兜底计划在 Provider 恢复后允许再取一次真实计划;`DAILY_PLAN_FALLBACK_RETRY_LIMIT = 3` 防住「Provider 就绪但生成始终失败」时每个 tick 重跑模型;重试计数按日期分桶,昨天用掉的额度不占今天的;真实计划到手即清空计数。归档侧靠已有的版本水位做 upsert,不会撞版本冲突。 - 预防规则:凡是写入了「降级/兜底」标记的数据,都要有一条链路消费这个标记——否则标记只是自我安慰。带日期的缓存键要问一句「如果这份数据是坏的,什么时候会被替换」,答不上来就是固化。 - 验证证据:`tests/test_p0_runtime_fixes.py::FallbackUpgradeTests` 8 项(含额度耗尽、跨日分桶、坏状态容错);VM 上当天计划保持 `source=llm v=2 10 段`,重试计数为空。 + +## 2026-07-27 — 固定天数的补算窗口,等于给「静默丢数据」定了个期限 + +- 阶段:P1 遗留缺陷清理(上轮 #14,连续四轮被推迟) +- 类型:数据一致性 +- 现象:`_agenda_closed_windows` 固定扫 `-3..+1` 天。停机超过 3 天,中间那些窗口既不会被补算,也不留任何痕迹——数据里就是一段空洞。而「快照数为 0」和「本来就没到时间」在结果上长得一模一样,所以这个缺陷挂了四轮都没人能从现象上发现它。 +- 根因:用「最近几天」近似「还没结算的部分」。这个近似在服务不间断时成立,恰好在最需要补算的场景(长时间停机)下失效。 +- 修复或规避:持久化 `agenda_last_settled` 游标,从游标往前扫;游标缺失时退回原来的 3 天,兼容旧数据。补算跨度上限 `AGENDA_SETTLE_MAX_CATCHUP_DAYS = 30`,超出部分**明确告警后**放弃——不是不允许有上限,是不允许静默截断。游标只在快照与结算都写完之后推进,且只前进不后退。 +- 预防规则:凡是「扫最近 N 天/条」的补偿逻辑,都要问一句「N 不够时会发生什么」。答案是「静默少算」就必须换成游标。任何截断都要留日志,否则「跑完了」和「跑了一部分」无法区分。 +- 验证证据:`tests/test_agenda_settle_cursor.py` 8 项(含停机 10 天补算、超上限告警、游标不回退、坏游标容错、旧字符串游标兼容)。 + +## 2026-07-27 — 幂等键格式与合同不符:一处双前缀,一处拿内部 id 当业务键 + +- 阶段:P3 遗留缺陷清理(P2-6) +- 类型:跨插件契约 +- 现象:`reconciliation_id` 本身已是 `reconciliation:{date}:{window}`,归档时又套一层前缀,落库键成了 `reconciliation:reconciliation:2026-07-24:早晨`;窗口快照则用内部 `snapshot_id` 拼成 `agenda_snapshot:snapshot-2026-07-24-下午`。合同 FROZEN 1.0 第 90 行推荐的是 `reconciliation:{date}:{window}` 与 `window_snapshot:{date}:{window}`。 +- 根因:拼键时顺手用了手边的 id,没有回看那个 id 自己是什么格式。键唯一且稳定,所以功能一直正常,只有格式不对——这类问题不会自己暴露。 +- 修复或规避:抽出 `_bot_personal_window_key(date, window, prefix=..., fallback=...)` 统一按合同格式拼;date/window 缺失时退回旧键,宁可格式不好看也不产出没有业务含义的键。**已落库的旧键保持不变**:结算与快照都是按窗口一次性写入的终态记录,不存在后续更新,键格式切换不会产生孤儿。 +- 预防规则:拼幂等键时先确认参与拼接的每个部分自己是什么格式,尤其是名字里已经带冒号的 id。跨插件的键格式以合同为准,合同里给了推荐格式就照抄,不要就地发明。 +- 验证证据:`tests/test_p3_key_and_clock.py::WindowKeyFormatTests` 3 项。 + +## 2026-07-27 — outbox 用系统时钟,与窗口归属不是同一套时间源 + +- 阶段:P3 遗留缺陷清理(P2-7) +- 类型:时间与时区 +- 现象:`bot_personal_outbox._now()` 直接取 `datetime.now().astimezone()`,而窗口归属、DTO 的 occurred_at 走的是插件的 `_environment_now`(带时区、可被测试与运维覆盖)。两套时钟意味着 outbox 的创建时间、重试时间可能与它描述的那个窗口不在同一天。 +- 根因:`_now()` 早就留了 `now` 参数,但所有调用点都没传——留了扩展点却没接上,比没留还隐蔽,因为签名看起来是对的。 +- 修复或规避:新增 `_memory_companion_clock()` 取插件时钟(取不到就退回 None,由 outbox 自己兜底),8 个 outbox 调用点全部带上 `now=`。测试用 2031 年的插件时钟与真实系统时钟拉开距离,时间戳落在 2031 才算通过。 +- 预防规则:函数留了 `now`/`clock` 这类可注入参数,就要有一条测试证明调用方真的传了——用一个不可能与系统时钟重合的值来断言,而不是断言「格式是 ISO」。 +- 验证证据:`tests/test_p3_key_and_clock.py::OutboxClockTests` 2 项;全量 231 项通过、联合 E2E 135/135。 diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index f75b43f..16fb17b 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -50,6 +50,22 @@ _BOT_PROFILE_HEADER = "【Bot 长期归档补充|当前日程以本地运行 _BRIDGE_UNPROBED = object() +def _bot_personal_window_key(date_value: Any, window_value: Any, *, prefix: str = "window_snapshot", fallback: str = "") -> str: + """按合同推荐格式拼窗口类幂等键:`{prefix}:{date}:{window}`。 + + 合同(FROZEN 1.0 第 90 行)推荐 `window_snapshot:{date}:{window}` 与 + `reconciliation:{date}:{window}`;此前一处用了内部 id 再加前缀( + `agenda_snapshot:snapshot-2026-07-24-下午`),另一处把已含前缀的 + reconciliation_id 又套了一层。date/window 缺失时退回旧键,宁可格式不好看 + 也不能产出一个没有业务含义的键。 + """ + date_text = _single_line(date_value, 40) + window_text = _single_line(window_value, 40) + if date_text and window_text: + return f"{prefix}:{date_text}:{window_text}" + return _single_line(fallback, 200) + + def _memory_companion_safe_float(value: Any, default: float, minimum: float = 0.0) -> float: helper = globals().get("_safe_float") if callable(helper): @@ -892,6 +908,21 @@ class MemoryCompanionAdapterMixin: result = await recorder(memory_type=memory_type, payload=body_payload, **common) return self._memory_companion_bridge_result(result, legacy=True) + def _memory_companion_clock(self) -> Any: + """outbox 用的时间源必须与窗口结算同一套。 + + outbox 原先内部直接取 `datetime.now()`,而窗口归属走的是插件的 + `_environment_now`(带时区、可被测试与运维覆盖)。两套时钟意味着 + 重试时间、创建时间与它们描述的那个窗口可能不在同一天。 + """ + getter = getattr(self, "_environment_now", None) + if callable(getter): + try: + return getter() + except Exception: + return None + return None + async def _memory_companion_record_bot_self_local( self, *, @@ -938,7 +969,7 @@ class MemoryCompanionAdapterMixin: outbox_record = None if strict and isinstance(data, dict): try: - outbox_record = enqueue_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], version=envelope["version"], payload=envelope) + outbox_record = enqueue_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], version=envelope["version"], payload=envelope, now=self._memory_companion_clock()) except PrivacyRejected as exc: logger.warning("[PrivateCompanion] Bot 个人 outbox 因隐私字段拒绝: path=%s reason=%s", exc.path, exc.reason) return @@ -966,16 +997,16 @@ class MemoryCompanionAdapterMixin: ) if strict and isinstance(data, dict) and isinstance(outbox_record, dict) and outbox_record.get("accepted", True): if result.get("ok"): - update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state="sent") + update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state="sent", now=self._memory_companion_clock()) else: error_code = _single_line(result.get("error_code"), 120) or "invalid_bridge_response" - update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state=self._memory_companion_archive_error_state(error_code), error_code=error_code) + update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state=self._memory_companion_archive_error_state(error_code), error_code=error_code, now=self._memory_companion_clock()) saver = getattr(self, "_schedule_data_save", None) if callable(saver): saver() except Exception as exc: if strict and isinstance(data, dict) and isinstance(outbox_record, dict) and outbox_record.get("accepted", True): - update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state="retry", error_code=type(exc).__name__) + update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state="retry", error_code=type(exc).__name__, now=self._memory_companion_clock()) saver = getattr(self, "_schedule_data_save", None) if callable(saver): saver() @@ -990,19 +1021,19 @@ class MemoryCompanionAdapterMixin: return 0 sent = 0 dirty = False - for record in due_outbox(data, limit=limit): + for record in due_outbox(data, limit=limit, now=self._memory_companion_clock()): try: envelope = record.get("payload") if isinstance(record.get("payload"), dict) else {} result = await asyncio.wait_for(self._memory_companion_send_bot_archive(bridge, envelope), timeout=1.2) if result.get("ok"): - update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state="sent") + update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state="sent", now=self._memory_companion_clock()) sent += 1 else: error_code = _single_line(result.get("error_code"), 120) or "invalid_bridge_response" - update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state=self._memory_companion_archive_error_state(error_code), error_code=error_code) + update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state=self._memory_companion_archive_error_state(error_code), error_code=error_code, now=self._memory_companion_clock()) dirty = True except Exception as exc: - update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state="retry", error_code=type(exc).__name__) + update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state="retry", error_code=type(exc).__name__, now=self._memory_companion_clock()) dirty = True saver = getattr(self, "_schedule_data_save", None) if callable(saver) and dirty: @@ -1054,7 +1085,8 @@ class MemoryCompanionAdapterMixin: # 本地快照会随窗口重算升版本;不透传则归档恒为 v1,同窗口重快照撞 version_conflict 进死信 "version": _safe_int(snapshot.get("version"), 1, 1, 10_000_000), }, - idempotency_key=f"agenda_snapshot:{snapshot_id}", + idempotency_key=_bot_personal_window_key( + snapshot.get("date"), snapshot.get("window"), fallback=snapshot_id), ) async def _memory_companion_record_observed_activity(self, activity: dict[str, Any]) -> None: if not isinstance(activity, dict) or not activity.get("activity_id"): @@ -1087,7 +1119,12 @@ class MemoryCompanionAdapterMixin: namespace="bot_agenda_history", kind="reconciliation", payload=dict(record), - idempotency_key=f"reconciliation:{_single_line(record.get('reconciliation_id'), 160)}", + # reconciliation_id 本身就是 "reconciliation:{date}:{window}",再加一层前缀 + # 会得到 reconciliation:reconciliation:...,与合同推荐格式不符 + idempotency_key=_bot_personal_window_key( + record.get("date"), record.get("window"), + prefix="reconciliation", + fallback=_single_line(record.get("reconciliation_id"), 160)), ) async def _memory_companion_record_daily_diary(self, diary: dict[str, Any]) -> None: diff --git a/tests/test_agenda_settle_cursor.py b/tests/test_agenda_settle_cursor.py new file mode 100644 index 0000000..93a2ca4 --- /dev/null +++ b/tests/test_agenda_settle_cursor.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +"""窗口结算游标回归(上轮 #14,连续四轮被推迟)。 + +`_agenda_closed_windows` 原本固定扫 `-3..+1` 天。停机超过 3 天,中间那些窗口 +既不会被补算,也不会留下任何痕迹——数据里就是一段静默空洞,而「快照数为 0」 +和「本来就没到时间」在结果上长得一模一样。 +""" +from __future__ import annotations + +import importlib +import pathlib +import sys +import types +import unittest +from datetime import date, datetime, timedelta, timezone + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import _host_stub # noqa: E402 + +_host_stub.install() + +_package_name = "_cursor_companion" +_package = types.ModuleType(_package_name) +_package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])] +sys.modules.setdefault(_package_name, _package) + +agenda_runtime = importlib.import_module(f"{_package_name}.agenda_runtime") +LOGGER_NAME = getattr(agenda_runtime.logger, "name", "astrbot") + +TZ = timezone(timedelta(hours=8)) +NOW = datetime(2026, 7, 27, 12, 0, 0, tzinfo=TZ) # 下午窗口进行中 + + +class Host(agenda_runtime.AgendaRuntimeMixin): + def __init__(self, cursor=None, snapshots=None): + self.data = {} + if cursor is not None: + self.data["agenda_last_settled"] = cursor + if snapshots: + self.data["window_snapshots"] = list(snapshots) + self.saves = 0 + + def _agenda_timezone_name(self) -> str: + return "Asia/Shanghai" + + def _schedule_data_save(self, delay: float = 0.0) -> None: + self.saves += 1 + + +def dates_of(pairs): + return sorted({d for d, _ in pairs}) + + +class SettleCursorTests(unittest.TestCase): + def test_without_a_cursor_it_keeps_the_old_three_day_window(self): + found = dates_of(Host()._agenda_closed_windows(NOW)) + self.assertEqual(min(found), (NOW.date() - timedelta(days=3)).isoformat()) + + def test_a_gap_longer_than_three_days_is_caught_up(self): + """这是 #14 的核心:停机 10 天后,第 4 天之前的窗口原本永远丢失。""" + cursor_date = (NOW.date() - timedelta(days=10)).isoformat() + found = dates_of(Host(cursor={"date": cursor_date, "window": "晚上"})._agenda_closed_windows(NOW)) + self.assertEqual(min(found), cursor_date) + old = (NOW.date() - timedelta(days=7)).isoformat() + self.assertIn(old, found, "停机期间的窗口没有被补算") + + def test_catchup_is_capped_and_says_so(self): + """超出上限就放弃,但必须留下告警——静默截断会被读成「已全部覆盖」。""" + cursor_date = (NOW.date() - timedelta(days=400)).isoformat() + host = Host(cursor={"date": cursor_date, "window": "晚上"}) + with self.assertLogs(LOGGER_NAME, level="WARNING") as captured: + found = dates_of(host._agenda_closed_windows(NOW)) + limit = agenda_runtime.AGENDA_SETTLE_MAX_CATCHUP_DAYS + self.assertEqual(min(found), (NOW.date() - timedelta(days=limit)).isoformat()) + self.assertTrue(any("补算上限" in line for line in captured.output), captured.output) + + def test_already_snapshotted_windows_are_not_repeated(self): + target = (NOW.date() - timedelta(days=1)).isoformat() + host = Host( + cursor={"date": target, "window": "深夜"}, + snapshots=[{"snapshot_id": f"snapshot-{target}-早晨"}], + ) + found = host._agenda_closed_windows(NOW) + self.assertNotIn((target, "早晨"), found) + self.assertIn((target, "下午"), found) + + +class CursorAdvanceTests(unittest.TestCase): + def test_cursor_moves_forward_and_persists(self): + host = Host() + host._agenda_note_settled("2026-07-20", "晚上") + self.assertEqual(host.data["agenda_last_settled"], {"date": "2026-07-20", "window": "晚上"}) + self.assertEqual(host.saves, 1, "游标必须落盘,否则重启后又退回固定窗口") + + def test_cursor_never_goes_backwards(self): + host = Host(cursor={"date": "2026-07-25", "window": "晚上"}) + host._agenda_note_settled("2026-07-20", "早晨") + self.assertEqual(host._agenda_settle_cursor_date(), "2026-07-25") + + def test_broken_cursor_falls_back_instead_of_crashing(self): + for bad in ("", "not-a-date", None, {"date": "坏值"}, ["列表"]): + with self.subTest(bad=bad): + self.assertEqual(Host(cursor=bad)._agenda_settle_cursor_date(), "") + + def test_legacy_plain_string_cursor_is_accepted(self): + """早期数据可能只存了一个日期字符串,不能因为形状不同就当成没有游标。""" + self.assertEqual(Host(cursor="2026-07-21")._agenda_settle_cursor_date(), "2026-07-21") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_p3_key_and_clock.py b/tests/test_p3_key_and_clock.py new file mode 100644 index 0000000..2631a02 --- /dev/null +++ b/tests/test_p3_key_and_clock.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +"""P2-6 / P2-7 回归:幂等键格式与 outbox 时钟来源。 + +两条都在遗留队列里挂了四轮: + +- P2-6:`reconciliation_id` 本身就是 `reconciliation:{date}:{window}`,再套一层 + 前缀会得到 `reconciliation:reconciliation:...`;窗口快照则用内部 id 拼成 + `agenda_snapshot:snapshot-2026-07-24-下午`。两者都偏离合同(FROZEN 1.0 第 90 行) + 推荐的 `window_snapshot:{date}:{window}` / `reconciliation:{date}:{window}`。 +- P2-7:outbox 内部直接取 `datetime.now()`,而窗口归属走插件的 `_environment_now`。 + 两套时钟意味着重试时间与它描述的窗口可能不在同一天。 +""" +from __future__ import annotations + +import asyncio +import importlib +import logging +import pathlib +import sys +import types +import unittest +from datetime import datetime, timedelta, timezone + +if "astrbot.api" not in sys.modules: + _astrbot = types.ModuleType("astrbot") + _api = types.ModuleType("astrbot.api") + _api.logger = logging.getLogger("test.astrbot") + _astrbot.api = _api + sys.modules.setdefault("astrbot", _astrbot) + sys.modules.setdefault("astrbot.api", _api) + +_package_name = "_p3_companion" +_package = types.ModuleType(_package_name) +_package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])] +sys.modules.setdefault(_package_name, _package) + +adapter_mod = importlib.import_module(f"{_package_name}.memory_companion_adapter") +MemoryCompanionAdapterMixin = adapter_mod.MemoryCompanionAdapterMixin + +TZ = timezone(timedelta(hours=8)) +# 刻意与系统时钟拉开距离:如果 outbox 还在用 datetime.now(),时间戳不会落在这一天 +PLUGIN_NOW = datetime(2031, 3, 4, 5, 6, 7, tzinfo=TZ) + + +class Bridge: + def __init__(self): + self.writes = [] + + async def record_bot_personal_memory(self, **kwargs): + self.writes.append(kwargs) + return {"ok": True, "record_id": "r1", "deduplicated": False, "version": 1, + "error_code": None, "action": "created"} + + +class Adapter(MemoryCompanionAdapterMixin): + def __init__(self): + self.bridge = Bridge() + self.data = {} + self.memory_companion_context_timeout_seconds = 1.0 + self._bridge_cache = self.bridge + self._bridge_cache_ts = 9999999999 + + def _memory_companion_bridge(self): + return self.bridge + + def _bot_self_record(self, namespace, payload, *, idempotency_key): + pass + + def _environment_now(self): + return PLUGIN_NOW + + def _schedule_data_save(self, delay: float = 0.0) -> None: + pass + + +def run(coro): + return asyncio.run(coro) + + +class WindowKeyFormatTests(unittest.TestCase): + def test_snapshot_key_follows_the_contract_format(self): + adapter = Adapter() + run(adapter._memory_companion_record_agenda_snapshot({ + "snapshot_id": "snapshot-2026-07-24-下午", "date": "2026-07-24", "window": "下午"})) + key = adapter.bridge.writes[0]["idempotency_key"] + self.assertEqual(key, "window_snapshot:2026-07-24:下午") + + def test_reconciliation_key_is_not_double_prefixed(self): + adapter = Adapter() + run(adapter._memory_companion_record_reconciliation({ + "reconciliation_id": "reconciliation:2026-07-24:早晨", + "date": "2026-07-24", "window": "早晨"})) + key = adapter.bridge.writes[0]["idempotency_key"] + self.assertEqual(key, "reconciliation:2026-07-24:早晨") + self.assertNotIn("reconciliation:reconciliation", key) + + def test_missing_date_or_window_falls_back_to_the_old_key(self): + """宁可格式不好看,也不能产出一个没有业务含义的键。""" + build = adapter_mod._bot_personal_window_key + self.assertEqual(build("", "下午", fallback="snapshot-x"), "snapshot-x") + self.assertEqual(build("2026-07-24", "", fallback="snapshot-x"), "snapshot-x") + self.assertEqual(build("2026-07-24", "下午"), "window_snapshot:2026-07-24:下午") + + +class OutboxClockTests(unittest.TestCase): + def test_outbox_timestamps_come_from_the_plugin_clock(self): + adapter = Adapter() + run(adapter._memory_companion_record_agenda_snapshot({ + "snapshot_id": "snapshot-2026-07-24-下午", "date": "2026-07-24", "window": "下午"})) + entries = adapter.data.get("bot_personal_outbox") or [] + self.assertTrue(entries, "严格类型没有进 outbox") + created = str(entries[-1].get("created_at") or "") + self.assertTrue(created.startswith("2031-03-04"), + f"outbox 仍在用系统时钟: created_at={created}") + + def test_clock_helper_survives_a_broken_environment_now(self): + class Broken(Adapter): + def _environment_now(self): + raise RuntimeError("时钟坏了") + + self.assertIsNone(Broken()._memory_companion_clock()) + + +if __name__ == "__main__": + unittest.main()