diff --git a/core/openmate_core/store.py b/core/openmate_core/store.py index b2a73ff..9fb7ba2 100644 --- a/core/openmate_core/store.py +++ b/core/openmate_core/store.py @@ -261,6 +261,9 @@ def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()): os.chmod(path, 0o600) self._lock = threading.RLock() self._read_lock = threading.Lock() + self._chat_lock = threading.Lock() # version publication only, never held while running SQL + self._chat_generation = 0 + self._chat_versions: Dict[str, int] = {} self.changes = 0 self.snapshot_scope = (0, "") # the /agent runs an account switch wiped (ids are never reused): a thread of the account before that still @@ -324,10 +327,11 @@ def close(self) -> None: # ---- small helpers ---- - def _tx(self, fn, *, count: bool = True): + def _tx(self, fn, *, count: bool = True, chat_ids: Optional[Iterable[str]] = None): """fn(db) in one write transaction. Whatever fails (fn, or the COMMIT itself: SQLITE_BUSY), the transaction is rolled back before the error goes up. A commit that changes rows invalidates cached chat reads unless the - caller opts out for bookkeeping that cannot affect those reads.""" + caller opts out for bookkeeping that cannot affect those reads. chat_ids can be filled by fn: None means + the affected chats are unknown, () means the write affects no chat or message rows.""" with self._lock: self._db.execute("BEGIN IMMEDIATE") try: @@ -335,7 +339,13 @@ def _tx(self, fn, *, count: bool = True): out = fn(self._db) self._db.execute("COMMIT") if count and self._db.total_changes != before: - self.changes += 1 + with self._chat_lock: + if chat_ids is None: + self._invalidate_chats() + else: + for cid in chat_ids: + self._chat_versions[cid] = self._chat_versions.get(cid, 0) + 1 + self.changes += 1 return out except BaseException: if self._db.in_transaction: @@ -345,6 +355,16 @@ def _tx(self, fn, *, count: bool = True): pass # the original error says more raise + def _invalidate_chats(self) -> None: + # Caller holds _chat_lock. + self._chat_generation += 1 + self._chat_versions.clear() + + def chat_versions(self, chat_ids: Iterable[str]) -> Tuple[int, Dict[str, int]]: + """The current generation and committed versions of the requested chats.""" + with self._chat_lock: + return self._chat_generation, {cid: self._chat_versions.get(cid, 0) for cid in chat_ids} + def _all(self, sql: str, args: Iterable = ()) -> List[sqlite3.Row]: with self._read_lock: return self._reader.execute(sql, tuple(args)).fetchall() @@ -387,10 +407,11 @@ def meta_get(self, key: str, default: str = "") -> str: return r["value"] if r else default def meta_set(self, key: str, value: str) -> None: - self._tx(lambda db: db.execute("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, value))) + self._tx(lambda db: db.execute("INSERT INTO meta (key, value) VALUES (?, ?) " + "ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, value)), chat_ids=()) def meta_delete(self, key: str) -> None: - self._tx(lambda db: db.execute("DELETE FROM meta WHERE key = ?", (key,))) + self._tx(lambda db: db.execute("DELETE FROM meta WHERE key = ?", (key,)), chat_ids=()) # ---- chats ---- @@ -423,7 +444,7 @@ def run(db): "ON CONFLICT(open_id) DO UPDATE SET chat_id = excluded.chat_id, at = excluded.at", (open_id, chat.id, now)) - self._tx(run) + self._tx(run, chat_ids=(chat.id,)) def chat_of_open_id(self, open_id: str) -> str: """The chat the service said has this open-platform id ("" when none did).""" @@ -444,7 +465,7 @@ def set_avatar(self, chat_id: str, value: str, now: Optional[float] = None) -> N self._tx(lambda db: db.execute( "INSERT INTO avatars (chat_id, value, checked) VALUES (?, ?, ?) " "ON CONFLICT(chat_id) DO UPDATE SET value = excluded.value, checked = excluded.checked", - (str(chat_id), str(value or ""), now or time.time()))) + (str(chat_id), str(value or ""), now or time.time())), chat_ids=()) def avatars(self, ids: Iterable[str]) -> Dict[str, Tuple[str, float]]: """{chat id: (picture, when it was asked)} of those of ids the service was asked about ("": it has none).""" @@ -474,7 +495,7 @@ def set_mute(self, chat_id: str, state: str, owner: str = "", now: Optional[floa self._tx(lambda db: db.execute( "INSERT INTO mutes (chat_id, state, checked, owner) VALUES (?, ?, ?, ?) " "ON CONFLICT(chat_id) DO UPDATE SET state = excluded.state, checked = excluded.checked, owner = excluded.owner", - (str(chat_id), state, now or time.time(), owner or ""))) + (str(chat_id), state, now or time.time(), owner or "")), chat_ids=()) def mutes(self, ids: Iterable[str], owner: str = "") -> Dict[str, Tuple[str, float]]: """{chat id: (state, when it was asked)} of those of ids the service was asked about for the account owner.""" @@ -503,7 +524,7 @@ def set_people_kinds(self, kinds: Dict[str, str], now: Optional[float] = None) - if rows: self._tx(lambda db: db.executemany( "INSERT INTO people (id, kind, checked) VALUES (?, ?, ?) " - "ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, checked = excluded.checked", rows)) + "ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, checked = excluded.checked", rows), chat_ids=()) def dismissed(self, keys: Iterable[str]) -> Dict[str, str]: """{key: version} of those of keys the user marked 处理完.""" @@ -523,10 +544,10 @@ def run(db): "ON CONFLICT(key) DO UPDATE SET version = excluded.version, at = excluded.at", (key, version, now)) db.execute("DELETE FROM dismissed WHERE at < ?", (now - 30 * 86400,)) - self._tx(run) + self._tx(run, chat_ids=()) def undismiss(self, key: str) -> None: - self._tx(lambda db: db.execute("DELETE FROM dismissed WHERE key = ?", (key,))) + self._tx(lambda db: db.execute("DELETE FROM dismissed WHERE key = ?", (key,)), chat_ids=()) def chats_of_messages(self, message_ids: Iterable[str]) -> List[str]: """The chats these stored messages are in.""" @@ -553,7 +574,7 @@ def run(db): db.execute("DELETE FROM dismissed WHERE at < ?", (now - 30 * 86400,)) # as dismiss: a month at most out[0] = True - self._tx(run) + self._tx(run, chat_ids=()) return out[0] def undismiss_if(self, key: str, expected: str) -> bool: @@ -563,7 +584,7 @@ def undismiss_if(self, key: str, expected: str) -> bool: def run(db): out[0] = db.execute("DELETE FROM dismissed WHERE key = ? AND version = ?", (key, expected)).rowcount > 0 - self._tx(run) + self._tx(run, chat_ids=()) return out[0] def count_since(self, since: float) -> dict: @@ -677,12 +698,14 @@ def add_messages(self, msgs: List[Message], from_history: bool, now: Optional[fl also has the message's placement and same_as when the backend read them, and, with a placement, the thread and quote of that same live reading (none of it stored: /agent keeps what it needs with its run).""" now = now or time.time() + changed = set() def run(db): new = [] for m in msgs: if not m.id or not m.chat_id: continue + before = db.total_changes if m.text and not m.text.strip(): m.text = "" # spaces alone are no text: it stays one to read again cur = db.execute( @@ -744,7 +767,10 @@ def run(db): (m.chat_id, m.id)).fetchone() if r is not None: new.append(_live_row(r, m)) # its first live delivery + if db.total_changes != before: + changed.add(m.chat_id) continue + changed.add(m.chat_id) if (m.type or "").upper() != "SYSTEM": db.execute( "INSERT INTO chats (id, updated, last_at) VALUES (?, ?, ?) " @@ -755,7 +781,7 @@ def run(db): new.append(_live_row(r, m)) return new - return self._tx(run) + return self._tx(run, chat_ids=changed) def message(self, chat_id: str, msg_id: str) -> Optional[dict]: r = self._one("SELECT " + _MESSAGE_COLUMNS + " FROM messages WHERE chat_id = ? AND id = ?", (chat_id, msg_id)) @@ -904,7 +930,8 @@ def put_name(self, user_id: str, name: str, chat_id: str = "", now: Optional[flo "INSERT INTO names (user_id, chat_id, name, updated) VALUES (?, ?, ?, ?) " "ON CONFLICT(user_id, chat_id) DO UPDATE SET name = excluded.name, updated = excluded.updated", (user_id, chat_id or "", name, now), - ) + ), + chat_ids=(), ) def name(self, user_id: str, chat_id: str = "") -> str: @@ -1018,7 +1045,7 @@ def put(db) -> bool: ) return True - return self._tx(put) + return self._tx(put, chat_ids=()) def run_wiped(self, run_id: str) -> bool: """The run was the account's signed in before, wiped by the switch: nothing is said or sent for it.""" @@ -1093,7 +1120,7 @@ def run(db): db.execute("INSERT OR IGNORE INTO gone (chat_id, at) VALUES (?, ?)", (chat_id, at)) db.execute("DELETE FROM autoreply WHERE chat_id = ?", (chat_id,)) - self._tx(run) + self._tx(run, chat_ids=(chat_id,)) def is_gone(self, chat_id: str) -> bool: """The account left or deleted this chat (chat_gone), and no newer message brought it back.""" @@ -1105,14 +1132,15 @@ def chats_back(self, latest: Dict[str, float]) -> int: latest = {c: at for c, at in latest.items() if c in gone} # nearly always none: no write then if not latest: return 0 - n = [0] + changed = set() def run(db): for cid, at in latest.items(): - n[0] += db.execute("DELETE FROM gone WHERE chat_id = ? AND at < ?", (cid, at)).rowcount + if db.execute("DELETE FROM gone WHERE chat_id = ? AND at < ?", (cid, at)).rowcount: + changed.add(cid) - self._tx(run) - return n[0] + self._tx(run, chat_ids=changed) + return len(changed) def chat_ids_named(self, name: str) -> List[str]: """The chats (none the account left) with exactly this name.""" @@ -1241,9 +1269,10 @@ def autoreply_chats(self) -> List[str]: def autoreply_set(self, chat_id: str, on: bool, now: Optional[float] = None) -> None: if on: - self._tx(lambda db: db.execute("INSERT OR IGNORE INTO autoreply (chat_id, at) VALUES (?, ?)", (chat_id, now or time.time()))) + self._tx(lambda db: db.execute("INSERT OR IGNORE INTO autoreply (chat_id, at) VALUES (?, ?)", + (chat_id, now or time.time())), chat_ids=()) else: - self._tx(lambda db: db.execute("DELETE FROM autoreply WHERE chat_id = ?", (chat_id,))) + self._tx(lambda db: db.execute("DELETE FROM autoreply WHERE chat_id = ?", (chat_id,)), chat_ids=()) def runs_prune(self, before: float, keep: int, protect=()) -> None: """Forget runs older than before, and all but the newest keep; never one still starting or running, nor one @@ -1264,7 +1293,7 @@ def run(db): now = time.time() for rid in [r for r, at in self._pruned_runs.items() if now - at > 86400.0]: del self._pruned_runs[rid] - for rid in self._tx(run): + for rid in self._tx(run, chat_ids=()): self._pruned_runs[rid] = now def run_count(self) -> int: @@ -1337,7 +1366,11 @@ def run(db): return runs with self._lock: # no run_put between the wipe and the ids it took out + before = self.changes self._wiped_runs.update(self._tx(run)) + if self.changes == before: # an empty wipe still starts a new generation + with self._chat_lock: + self._invalidate_chats() self.snapshot_scope = (self.snapshot_scope[0] + 1, owner or self.snapshot_scope[1]) self._wiped_runs.update(self._pruned_runs) # pruned lately: a thread may still hold one of those too self._pruned_runs.clear() diff --git a/core/openmate_core/ui.py b/core/openmate_core/ui.py index cf29018..3b55150 100644 --- a/core/openmate_core/ui.py +++ b/core/openmate_core/ui.py @@ -11,7 +11,7 @@ import contextlib import math import sys -from collections import deque +from collections import OrderedDict, deque import datetime as _dt import hashlib import json @@ -19,7 +19,7 @@ import threading import time import urllib.parse -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Tuple from . import views from .agent import BOT_THREAD_MOST @@ -406,6 +406,7 @@ def run(): NEEDS_HOURS = 24 # an @me or a direct message older than this no longer needs the user (setting needs_hours) +NEEDS_CACHE_CHATS = 600 TALK_GAP = 3600.0 # the other side answered within this of my last message: the talk goes on, it is not a request DONE_SLACK = 60.0 # a service's done mark this much older than a need's latest line still covers it (clock, rounding) REOPENED = "reopened:" # a 处理完 mark's version brought back (恢复): the service's done mark leaves that one alone @@ -442,6 +443,65 @@ def _talk_closed(msgs: List[dict], run: List[dict]) -> bool: return not any(asks_something(r) for r in run) +class _NeedsMessages(NamedTuple): + last: dict + latest_at: float + closed: bool + mentioned: bool + mentions: List[dict] + senders: set + + @classmethod + def from_rows(cls, rows: List[dict]) -> Optional[_NeedsMessages]: + messages = [r for r in rows if not views.is_system(r) and views.has_content(r)] + run = views.unanswered_run(messages) + if not run: + return None + return cls(run[-1], max(r.get("at") or 0 for r in rows), _talk_closed(messages, run), + any(r["at_me"] for r in run), [r for r in rows if r.get("at_me") and not r.get("mine")], + {r.get("sender_id") for r in rows if not r.get("mine")}) + + +class _NeedsMessagesCache: + """Share the message-derived parts of needs(), including the older @me, as read-only data across draws.""" + + def __init__(self): + self._lock = threading.Lock() + self._scope = None + self._entries: OrderedDict[str, Tuple[int, int, Optional[_NeedsMessages]]] = OrderedDict() + + def read(self, store, chat_ids: Iterable[str], limit: int = 60) -> Dict[str, Optional[_NeedsMessages]]: + out, missing = {}, {} + with self._lock: + generation, versions = store.chat_versions(chat_ids) + scope = (store, generation) + if scope != self._scope: + self._entries.clear() + self._scope = scope + for cid, version in versions.items(): + hit = self._entries.get(cid) + if hit is not None and hit[:2] == (version, limit): + self._entries.move_to_end(cid) + out[cid] = hit[2] + else: + missing[cid] = version + if not missing: + return out + + loaded = {cid: _NeedsMessages.from_rows(rows) for cid, rows in store.inbox_rows_many(missing, limit).items()} + with self._lock: + current, versions = store.chat_versions(missing) + if scope == self._scope and generation == current: + for cid, summary in loaded.items(): + if missing[cid] == versions[cid]: # a newer commit may have landed during the read + self._entries[cid] = (versions[cid], limit, summary) + self._entries.move_to_end(cid) + while len(self._entries) > NEEDS_CACHE_CHATS: + self._entries.popitem(last=False) + out.update(loaded) + return out + + class ChatsToday: """What needs the user in the chats, from the store: unanswered direct chats and @me, today's traffic.""" @@ -511,27 +571,28 @@ def _read_needs(self, now, hours, me, only): oldest = now - horizon chats = app.store.chats_since(now - window, app.timing.inbox_most if only is None else len(only), only=only) expires = min((c["last_at"] + window for c in chats), default=float("inf")) - batched = app.store.inbox_rows_many(c["id"] for c in chats) + cache = self._cache.get("messages") + if cache is None: + cache = self._cache.setdefault("messages", _NeedsMessagesCache()) + batched = cache.read(app.store, (c["id"] for c in chats)) for chat in chats: - rows = batched[chat["id"]] - messages = [r for r in rows if not views.is_system(r) and views.has_content(r)] - run = views.unanswered_run(messages) + messages = batched[chat["id"]] dm = views.chat_kind(chat) == "dm" - if not run or not dm and not any(r["at_me"] for r in run): + if messages is None or not dm and not messages.mentioned: continue - if dm and _talk_closed(messages, run): + if dm and messages.closed: closed += 1 continue - last = run[-1] + last = messages.last thing = {"kind": "dm" if dm else "mention", "title": views.chat_name(chat, chat["id"]), "sender": views.sender_of(last, me), "preview": one_line(views.text_of(last), 200), "last": last["id"]} - thing["_at"] = max((r.get("at") or 0) for r in rows) if rows else 0 - thing["_version_at"] = next((r.get("at") or 0 for r in rows if r.get("id") == thing.get("last")), thing["_at"]) + thing["_at"] = messages.latest_at + thing["_version_at"] = last.get("at") or 0 thing["_chat"] = chat if thing["kind"] == "dm": - who = {chat.get("peer_id") or ""} if chat.get("peer_id") else {r.get("sender_id") for r in rows if not r.get("mine")} + who = {chat["peer_id"]} if chat.get("peer_id") else messages.senders else: - thing["_ats"] = [r for r in rows if r.get("at_me") and not r.get("mine")] + thing["_ats"] = messages.mentions who = {r.get("sender_id") for r in thing["_ats"]} thing["_who"] = {w for w in who if w} out.append(thing) diff --git a/extensions/openmate-feishu/openmate_feishu/mail_store.py b/extensions/openmate-feishu/openmate_feishu/mail_store.py index 63da4ec..1c375e4 100644 --- a/extensions/openmate-feishu/openmate_feishu/mail_store.py +++ b/extensions/openmate-feishu/openmate_feishu/mail_store.py @@ -50,7 +50,7 @@ def setup(db): db.execute(sql) self._prune_reply_cards(db, now) - store._tx(setup) + store._tx(setup, chat_ids=()) def settings(self, owner): return json.loads(self.store.meta_get("mail:" + owner, "{}")) @@ -74,7 +74,7 @@ def write(db): (_CARD_MOST,)) return True - return self.store._tx(write) + return self.store._tx(write, chat_ids=()) def reply_card(self, digest, now): value = self.store._one("SELECT card FROM mail_reply_cards WHERE digest=? AND saved_at>?", @@ -132,7 +132,7 @@ def write(db): db.execute("INSERT INTO meta(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value " "WHERE value!=excluded.value", ("mail:" + owner, saved)) return changed or db.total_changes != before, bool(eligible) - return self.store._tx(write) + return self.store._tx(write, chat_ids=()) def recent(self, owner, since, now, limit, *, inbox=False, unread_only=False, query=""): clauses = ["owner=?", "at BETWEEN ? AND ?"] diff --git a/extensions/openmate-feishu/openmate_feishu/meeting_store.py b/extensions/openmate-feishu/openmate_feishu/meeting_store.py index e884e3c..f843a78 100644 --- a/extensions/openmate-feishu/openmate_feishu/meeting_store.py +++ b/extensions/openmate-feishu/openmate_feishu/meeting_store.py @@ -44,7 +44,7 @@ def _row(raw): class MeetingStore: def __init__(self, store): self.store = store - store._tx(self._setup) + store._tx(self._setup, chat_ids=()) @staticmethod def _setup(db): @@ -64,7 +64,7 @@ def write(db): "INSERT INTO meetings(meeting_id, owner, topic, app_link, updated) VALUES (?, ?, ?, ?, ?) " "ON CONFLICT(meeting_id) DO NOTHING", [(mid, owner, topic, link, now) for mid, (topic, link) in found.items()]) - self.store._tx(write) + self.store._tx(write, chat_ids=()) def known(self, owner, found): if not found: @@ -103,7 +103,7 @@ def write(db): db.execute("UPDATE meetings SET " + ", ".join(key + "=?" for key in values) + " WHERE meeting_id=? AND owner=?", (*values.values(), mid, owner)) return notify - return self.store._tx(write) + return self.store._tx(write, chat_ids=()) def recent(self, owner, since, now, limit, *, view="", query=""): columns = _BRIEF @@ -153,4 +153,4 @@ def offered(self, owner, ids): return False return self.store._tx(lambda db: db.executemany( "UPDATE meetings SET archive_offered=1 WHERE owner=? AND meeting_id=? AND archive_offered=0", - [(owner, mid) for mid in ids]).rowcount > 0) + [(owner, mid) for mid in ids]).rowcount > 0, chat_ids=()) diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index 080046c..94788a8 100644 --- a/extensions/openmate-feishu/persona-extension.json +++ b/extensions/openmate-feishu/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.76", + "version": "0.11.77", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index 3d98a64..c138773 100644 --- a/extensions/openmate-wechat/persona-extension.json +++ b/extensions/openmate-wechat/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.70", + "version": "0.1.71", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/packages/openmate-feishu/0.11.77/openmate-feishu-0.11.77.tar.gz b/packages/openmate-feishu/0.11.77/openmate-feishu-0.11.77.tar.gz new file mode 100644 index 0000000..fa6829a Binary files /dev/null and b/packages/openmate-feishu/0.11.77/openmate-feishu-0.11.77.tar.gz differ diff --git a/packages/openmate-wechat/0.1.71/openmate-wechat-0.1.71.tar.gz b/packages/openmate-wechat/0.1.71/openmate-wechat-0.1.71.tar.gz new file mode 100644 index 0000000..4b58437 Binary files /dev/null and b/packages/openmate-wechat/0.1.71/openmate-wechat-0.1.71.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index ab95e3c..c881900 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,7 +9,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.76", + "version": "0.11.77", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -534,9 +534,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.76/openmate-feishu-0.11.76.tar.gz", - "sha256": "a628e572fd8ba8b5d6d9840a7b0384f4991848c068362053da381156e2959327", - "size": 413811 + "url": "packages/openmate-feishu/0.11.77/openmate-feishu-0.11.77.tar.gz", + "sha256": "a13063ea58c1c06d7c61075ee5de2e82eefdbc944214c49021033e7f8752f00c", + "size": 414856 } ] }, @@ -545,7 +545,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.70", + "version": "0.1.71", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -842,9 +842,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.70/openmate-wechat-0.1.70.tar.gz", - "sha256": "ed0b87965955197b7c05e06fa72efe3837854ca75aad471c4f5ebdf10f26f31d", - "size": 310916 + "url": "packages/openmate-wechat/0.1.71/openmate-wechat-0.1.71.tar.gz", + "sha256": "dad07dc9350adb22378693049c8bd04e422108d0bb4d4305dbbf2fe62b5daa00", + "size": 311944 } ] } diff --git a/tests/test_snapshot_perf.py b/tests/test_snapshot_perf.py index 2c82e24..9cbe788 100644 --- a/tests/test_snapshot_perf.py +++ b/tests/test_snapshot_perf.py @@ -2,7 +2,9 @@ import datetime as dt import os +import random import stat +import statistics import tempfile import threading import time @@ -31,6 +33,12 @@ def open_store(self): self.addCleanup(store.close) return store + def chats_today(self, most=200): + app = types.SimpleNamespace(store=self.store, tz=dt.timezone.utc, me_name=lambda: "我", backend=None, + timing=types.SimpleNamespace(inbox_window=86400, inbox_most=most)) + app.people = People(app) + return ui.ChatsToday(app) + def test_default_transaction_write_invalidates_cached_needs(self): self.store.upsert_chat(Chat("dm", "dm", "旧会话名", peer_id="person")) self.store.add_messages([Message("dm-1", "dm", 1, sender_id="person", text="在吗?", at=time.time())], False) @@ -39,8 +47,10 @@ def test_default_transaction_write_invalidates_cached_needs(self): page = ui.ChatsToday(app) self.assertEqual([t["title"] for t in page.needs()], ["旧会话名"]) before = self.store.changes + generation, _ = self.store.chat_versions(["dm"]) self.store._tx(lambda db: db.execute("UPDATE chats SET name = '新会话名' WHERE id = 'dm'")) self.assertEqual(self.store.changes, before + 1) + self.assertEqual(self.store.chat_versions(["dm"]), (generation + 1, {"dm": 0})) self.assertEqual([t["title"] for t in page.needs()], ["新会话名"]) now = time.time() @@ -155,11 +165,8 @@ def test_needs_batches_and_reuses_reads_until_committed_changes(self): msgs.extend(Message(str(j), cid, j, sender_id="member", text="请确认", at=now, at_me=j == 1) for j in range(1, 64)) self.store.add_messages(msgs, False) - app = types.SimpleNamespace(store=self.store, tz=dt.timezone.utc, me_name=lambda: "我", backend=None, - timing=types.SimpleNamespace(inbox_window=86400, inbox_most=200), - platform=types.SimpleNamespace(name="fixture")) - app.people = People(app) - one, two = ui.ChatsToday(app), ui.ChatsToday(app) + one = self.chats_today() + two = ui.ChatsToday(one.app) with patch.object(self.store, "_all", wraps=self.store._all) as queries: self.assertEqual(len(one.needs()), 21) self.assertEqual({t["_version"] for t in one.needs() if t["kind"] == "mention"}, {"1"}) @@ -175,7 +182,7 @@ def test_needs_batches_and_reuses_reads_until_committed_changes(self): (lambda: self.store.set_mute("group-0", "muted"), 0), (lambda: self.store.set_avatar("group-0", "synthetic"), 0), ] - for write, expected in writes: + for i, (write, expected) in enumerate(writes): with self.subTest(write=write): before = self.store.changes write() @@ -183,10 +190,156 @@ def test_needs_batches_and_reuses_reads_until_committed_changes(self): queries.reset_mock() self.assertEqual(len(two.needs()), expected) self.assertGreater(queries.call_count, 0) + self.assertEqual(self.recent_query_ids(queries), ["dm"] if i == 0 else []) queries.reset_mock() self.assertEqual(one.needs(), two.needs()) self.assertEqual(queries.call_count, 0) + @staticmethod + def recent_query_ids(queries): + return [cid for sql, args in (call.args for call in queries.call_args_list) + if "FROM messages WHERE chat_id = ? ORDER BY position DESC" in sql for cid in args[::2]] + + def test_needs_incremental_matches_full_after_chat_writes(self): + now = time.time() + rng = random.Random(1703) + store = self.store + ids = ["dm-%d" % i for i in range(4)] + ["group-%d" % i for i in range(4)] + store.wipe_account_data("first") + for cid in ids: + store.upsert_chat(Chat(cid, cid.split("-")[0], cid)) + store.add_messages([Message(str(j), cid, j, sender_id="peer", text="请确认?", at=now - 100 + j, + at_me=cid.startswith("group-") and j == 2) for j in range(1, 65)], False) + page, full = self.chats_today(), self.chats_today() + + def compare(): + got = page.needs() + full._cache.clear() # discard both levels so the same Store reads every chat again + self.assertEqual(got, full.needs()) + self.assertEqual((page.done, page.bots, page.closed, page.expired), + (full.done, full.bots, full.closed, full.expired)) + return {t["_chat"]["id"]: t for t in got} + + group = rng.choice(ids[4:]) + self.assertEqual(compare()[group]["_version"], "2") # older @ outside the 60 recent rows + for mode in ("edit", "block", "recall"): + row = Message("2", group, 2, sender_id="peer", text=mode, at=now - 98, edited=True, + blocked=mode == "block", type="SYSTEM" if mode == "recall" else "TEXT") + with self.subTest(mode=mode), patch.object(store, "_all", wraps=store._all) as queries: + store.add_messages([row], False) + got = page.needs() + self.assertEqual(self.recent_query_ids(queries), [group]) + compared = compare() + self.assertEqual(got, list(compared.values())) + if mode == "recall": + self.assertNotIn(group, compared) + else: + self.assertEqual(compared[group]["preview"], mode) + + answered = rng.choice([cid for cid in ids[4:] if cid != group]) + self.assertIn(answered, compare()) + store.add_messages([Message("old-reply", answered, 3, mine=True, text="已回复", at=now - 97)], True) + self.assertNotIn(answered, compare()) # the recovered @ is older than this reply, which is also outside the recent rows + + for pos in range(65, 80): + changed = rng.sample(ids, 3) + store.add_messages([Message(str(pos), cid, pos, sender_id="peer", text="还有一个问题?", at=now + pos, + mine=i == 1, at_me=i == 2) for i, cid in enumerate(changed)], False) + with patch.object(store, "_all", wraps=store._all) as queries: + page.needs() + self.assertCountEqual(self.recent_query_ids(queries), changed) + compare() + + gone, stays = rng.sample(ids, 2) + store.chat_gone(gone, now=now + 100) + store.chat_gone(stays, now=now + 100) + self.assertNotIn(gone, compare()) + generation, versions = store.chat_versions([gone, stays]) + self.assertEqual(store.chats_back({gone: now + 101, stays: now + 99}), 1) + self.assertEqual(store.chat_versions([gone, stays]), (generation, {**versions, gone: versions[gone] + 1})) + store.upsert_chat(Chat(gone, "dm", "复用会话名")) + store.add_messages([Message("back", gone, 100, text="回来了?", at=now + 101)], False) + self.assertEqual(compare()[gone]["title"], "复用会话名") + + store.wipe_account_data("second") + self.assertEqual(store.chat_versions(ids), (generation + 1, dict.fromkeys(ids, 0))) + self.assertEqual(compare(), {}) + store.upsert_chat(Chat(gone, "dm", "新账号")) + store.add_messages([Message("back", gone, 100, text="新账号的消息?", at=now + 101)], False) + self.assertEqual(compare()[gone]["preview"], "新账号的消息?") + + def test_needs_message_cache_evicts_least_recently_used_chat_and_keys_by_limit(self): + cache = ui._NeedsMessagesCache() + with patch.object(ui, "NEEDS_CACHE_CHATS", 3), patch.object(self.store, "_all", wraps=self.store._all) as queries: + cache.read(self.store, ["a", "b", "c"]) + cache.read(self.store, ["a"]) + cache.read(self.store, ["d"]) + queries.reset_mock() + cache.read(self.store, ["a", "c", "d"]) + self.assertEqual(self.recent_query_ids(queries), []) + cache.read(self.store, ["b"]) + cache.read(self.store, ["d"], limit=10) + self.assertEqual(self.recent_query_ids(queries), ["b", "d"]) + self.assertEqual(len(cache._entries), 3) + + def test_chat_versions_ignore_rolled_back_and_noop_writes(self): + store = self.store + msg = Message("1", "dm", 1, text="请确认?", at=time.time()) + store.add_messages([msg], False) + before = store.changes, store.chat_versions(["dm"]) + + def fail(db): + db.execute("DELETE FROM messages") + raise ValueError("synthetic rollback") + + with self.assertRaises(ValueError): + store._tx(fail) + store.add_messages([msg], False) + self.assertEqual((store.changes, store.chat_versions(["dm"])), before) + self.assertIsNotNone(store.message("dm", "1")) + + def test_needs_message_cache_keeps_newer_read_when_commit_overlaps(self): + now = time.time() + store = self.store + store.add_messages([Message("before", "dm", 1, text="之前", at=now)], False) + cache = ui._NeedsMessagesCache() + read = store.inbox_rows_many + + def read_then_commit(chat_ids, limit): + before = read(chat_ids, limit) + store.add_messages([Message("after", "dm", 2, text="之后", at=now)], False) + with patch.object(store, "inbox_rows_many", read): + self.assertEqual(cache.read(store, ["dm"])["dm"].last["id"], "after") + return before + + with patch.object(store, "inbox_rows_many", side_effect=read_then_commit): + self.assertEqual(cache.read(store, ["dm"])["dm"].last["id"], "before") + with patch.object(store, "inbox_rows_many", wraps=read) as reads: + self.assertEqual(cache.read(store, ["dm"])["dm"].last["id"], "after") + reads.assert_not_called() + + def test_needs_recompute_after_single_chat_write_at_scale(self): + now = time.time() + for i in range(387): + cid = "chat-%03d" % i + self.store.upsert_chat(Chat(cid, "dm" if i % 5 == 0 else "group", cid, peer_id="peer-%d" % i)) + self.store.add_messages([ + Message(str(j), cid, j, sender_id="peer-%d" % i, text="请确认这个测试条目?", at=now - 500 + j, + mine=j == 210, at_me=j == 300 and i % 3 == 0) + for j in range(1, 415) + ], False) + self.assertEqual(self.store.message_count(), 160218) + page = self.chats_today(most=387) + self.assertTrue(page.needs()) + timings = [] + for i in range(9): + self.store.add_messages([Message("latest", "chat-%03d" % i, 415, text="还有一个问题?", at=now + i)], False) + start = time.perf_counter() + page.needs() + timings.append((time.perf_counter() - start) * 1000) + print("needs() 387 chats / 160218 messages, one chat changed: median %.2f ms, range %.2f–%.2f ms" + % (statistics.median(timings), min(timings), max(timings)), flush=True) + class RenderDiagnosticsTest(unittest.TestCase): def test_watchdog_dumps_a_blocked_render_once_and_limits_an_hour(self):