"""Each rule line a session is shown, whether it was opened after, and what that history says about where a rule is worth delivering. Three calls, one table (`rule_deliveries`): - `record` — from the plugin doors that know the session: every line an arm rendered, full or repeat. Within a bound request the rows wait in a buffer until the door's payload is assembled, and `flush` writes only the lines that made it into the payload (`hook_payload.fit`). - `mark_opened` — the session opened a rule: the latest unopened delivery of it in that session gets the stamp. An open with no delivery behind it (the agent looked a rule up unprompted) stamps nothing. A line for a rule the session has already opened is stamped as it is written: it reached a reader who has the rule. - `history` — for the ordering function: each rule's smoothed open rate at the place it is about to be delivered, over the last `HISTORY_DAYS`. An open rate counts only deliveries that carry the plugin version (`REPORTS_OPENS`): a plugin that does not send it does not report opens either, so its deliveries would read as never opened however often they were read. Deliveries are kept `RETAIN_DAYS` and pruned daily: enough history to rank on and to read adherence from, without a row per tool call accumulating forever. """ from __future__ import annotations import logging import re from contextvars import ContextVar from datetime import datetime, timedelta, timezone from sqlalchemy import and_, case, delete, func, select, tuple_, update from grimoire.models import async_session from grimoire.models.rule_delivery import FORMS, FULL, REPEAT, RuleDelivery from grimoire.services import rule_order from grimoire.services.background import spawn logger = logging.getLogger(__name__) HISTORY_DAYS = 90 RETAIN_DAYS = 180 # An open counts against a delivery made within this window before it; an # older one was read by a context that is long gone. OPEN_WINDOW = timedelta(hours=6) _SESSION_MAX = 200 _UNSAFE = re.compile(r"[^A-Za-z0-9._-]") # The session a plugin request is delivering to, bound once per request by the # plugin routes so the arms several calls deep record against it without every # signature between carrying it. Unbound (the MCP door, a test) records nothing. _session: ContextVar[str] = ContextVar("rule_delivery_session", default="") # Rows rendered during the bound request, written by `flush`. _pending: ContextVar[list | None] = ContextVar("rule_delivery_pending", default=None) # The plugin version that sent the bound request (`X-Grimoire-Plugin`). _plugin: ContextVar[str] = ContextVar("rule_delivery_plugin", default="") _PLUGIN_MAX = 64 # The deliveries an open rate is read from: those whose plugin reports opens. REPORTS_OPENS = RuleDelivery.plugin.is_not(None) def bind_session(session_id: str | None, plugin: str | None = None) -> None: _session.set(clean_session(session_id)) _plugin.set(_UNSAFE.sub("_", (plugin or "").strip())[:_PLUGIN_MAX]) _pending.set([]) # The record ledger delivers to the same session, under the same binding. from grimoire.services import record_deliveries record_deliveries.reset() def flush(kept: set[int] | None = None) -> None: """Write this request's buffered rows: those for rules in `kept`, or all of them when `kept` is None. Rows for a line the payload left out are dropped, since the session was never shown it.""" rows = _pending.get() if not rows: return _pending.set([]) if kept is not None: rows = [r for r in rows if r["rule_id"] in kept] if rows: spawn(_insert(rows), site="rule_delivery_write") def bound() -> bool: """Whether this request delivers to a known session — the doors that record deliveries are the ones that read their history back.""" return bool(_session.get()) def current_session() -> str: """The session this request delivers to, or "" outside a plugin request.""" return _session.get() def current_plugin() -> str | None: """The plugin version that sent this request, or None when it sent none.""" return _plugin.get() or None def clean_session(session_id: str | None) -> str: # The plugin's own filename-safe form of the id, so a hook that sends the # raw id and one that sends the safe one name the same session. return _UNSAFE.sub("_", (session_id or "").strip())[:_SESSION_MAX] def record( user_id: int, session_id: str | None, source: str, lines: list[tuple[int, str, str]], ) -> None: """Record delivered lines: `(rule_id, at, form)` each. A no-op without a session, since an open could never be tied back. `session_id` None means the one bound for this request, whose rows wait for `flush`.""" sid = clean_session(_session.get() if session_id is None else session_id) if not sid or not lines: return plugin = _plugin.get() or None try: rows = [ {"user_id": int(user_id), "session_id": sid, "rule_id": int(rid), "source": source, "at": str(at or source), "form": form if form in FORMS else FULL, "plugin": plugin} for rid, at, form in lines ] except Exception: # noqa: BLE001 - observation never breaks the observed logger.debug("rule delivery payload build failed", exc_info=True) return pending = _pending.get() if session_id is None else None if pending is not None: pending.extend(rows) return spawn(_insert(rows), site="rule_delivery_write") async def _insert(rows: list[dict]) -> None: now = datetime.now(timezone.utc) async with async_session() as session: read = await _read_already(session, rows, now) for row in rows: if (row["user_id"], row["session_id"], row["rule_id"]) in read: row["opened_at"] = now session.add_all(RuleDelivery(**row) for row in rows) await session.commit() async def _read_already(session, rows: list[dict], now: datetime) -> set: """`{(user_id, session_id, rule_id)}` among these rows that the session opened within `OPEN_WINDOW` before now. A line for a rule the session has already read is delivered to a reader who has it, so it is stamped opened as it is written: the open rate, the adherence readout and the weighing pass all read "opened" as "the session had this rule", and a rule read early in a long session is no less read when it arrives again later. Older opens do not count, for the reason `OPEN_WINDOW` gives. """ keys = {(r["user_id"], r["session_id"], r["rule_id"]) for r in rows} found = await session.execute( select(RuleDelivery.user_id, RuleDelivery.session_id, RuleDelivery.rule_id) .where( tuple_(RuleDelivery.user_id, RuleDelivery.session_id, RuleDelivery.rule_id).in_(list(keys)), RuleDelivery.opened_at >= now - OPEN_WINDOW, ) .distinct() ) return {tuple(k) for k in found.all()} async def mark_opened(user_id: int, session_id: str | None, rule_id: int) -> bool: """Stamp the latest unopened delivery of this rule in this session. Returns whether a delivery was stamped. Only that one: a rule delivered five times and opened once was opened after the fifth line, and the four before it were passed over. """ sid = clean_session(session_id) if not sid or not rule_id: return False now = datetime.now(timezone.utc) async with async_session() as session: latest = (await session.execute( select(RuleDelivery.id) .where( RuleDelivery.user_id == user_id, RuleDelivery.session_id == sid, RuleDelivery.rule_id == rule_id, RuleDelivery.opened_at.is_(None), RuleDelivery.delivered_at >= now - OPEN_WINDOW, ) .order_by(RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc()) .limit(1) )).scalar_one_or_none() if latest is None: return False await session.execute( update(RuleDelivery).where(RuleDelivery.id == latest).values(opened_at=now) ) await session.commit() return True async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float]: """`{rule_id: smoothed open rate}` at each pair's place, for this user. A rule with no delivery there is left out, which the ordering reads as unknown rather than as never opened. So is one delivered only to sessions whose plugin does not report opens. """ wanted = list(dict.fromkeys((int(rid), str(at)) for rid, at in pairs)) if not wanted: return {} since = datetime.now(timezone.utc) - timedelta(days=HISTORY_DAYS) async with async_session() as session: rows = (await session.execute( select( RuleDelivery.rule_id, RuleDelivery.at, func.count(RuleDelivery.id), func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)), ) .where( RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since, REPORTS_OPENS, tuple_(RuleDelivery.rule_id, RuleDelivery.at).in_(wanted), ) .group_by(RuleDelivery.rule_id, RuleDelivery.at) )).all() return { int(rid): rule_order.opened_rate(int(delivered), int(opened or 0)) for rid, _at, delivered, opened in rows } async def retired(user_id: int, rule_ids: list[int]) -> set[int]: """Which of these rules this session has already been reminded of. A rule's life in a session is one full line, then one reminder, then silence: retired is "the latest delivery of it in the bound session was a reminder". A full delivery re-arms it, which is what happens once the plugin's ledger forgets it (after a compaction, or as it ages out): the next line is full again, then one reminder, then silence again. """ sid = _session.get() wanted = sorted({int(r) for r in rule_ids}) if not sid or not wanted: return set() async with async_session() as session: rows = (await session.execute( select(RuleDelivery.rule_id, RuleDelivery.form) .where( RuleDelivery.user_id == user_id, RuleDelivery.session_id == sid, RuleDelivery.rule_id.in_(wanted), ) .distinct(RuleDelivery.rule_id) .order_by(RuleDelivery.rule_id, RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc()) )).all() return {int(rid) for rid, form in rows if form == REPEAT} async def prune(retain_days: int = RETAIN_DAYS) -> int: """Delete deliveries older than `retain_days`, the adherence verdicts on them (`rule_adherence`), which mean nothing without their delivery, and the record deliveries and gate stops of the same age (`record_deliveries`, `gate_stops`).""" from grimoire.services import rule_adherence cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days) async with async_session() as session: result = await session.execute( delete(RuleDelivery).where(and_(RuleDelivery.delivered_at < cutoff)) ) await session.commit() await rule_adherence.prune(cutoff) from grimoire.services import gate_stops, record_deliveries await record_deliveries.prune(cutoff) await gate_stops.prune(cutoff) return int(result.rowcount or 0) _prune_task = None async def _prune_tick() -> None: try: removed = await prune() if removed: logger.info("Rule delivery retention: deleted %d row(s)", removed) except Exception: logger.exception("Rule delivery retention failed") def start_prune_loop() -> None: global _prune_task if _prune_task is None or _prune_task.done(): from grimoire.services.background import start_periodic _prune_task = start_periodic(86400, _prune_tick, label="rule_delivery_retention") # daily