fix(7733): a rule's open rate counts only deliveries whose plugin reports opens
CI & Build / TypeScript typecheck (push) Canceled after 0s
CI & Build / Plugin hooks (push) Canceled after 0s
CI & Build / Python lint (push) Canceled after 0s
CI & Build / Python tests (push) Canceled after 0s
CI & Build / integration (push) Canceled after 0s
CI & Build / Build & push image (push) Canceled after 0s

Each rule line a hook delivers now records the plugin version that asked for
it (the X-Grimoire-Plugin header every hook request sends). The open rate
used to order rules, and the delivery history the weighing pass reads,
count only deliveries that carry one.

A plugin before 2026.11.22.2312 never reported an open of a rule a hook had
just named, so every delivery made to such a session read as unopened. The
server shipped delivery recording from dev on 2026-11-22. The plugin ships
from main, and a running session keeps the plugin it started with, so those
sessions kept arriving. They are why opens read about 1 in 600. Existing
rows have no version and drop out of the rate; nothing is deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 15:52:42 -05:00
co-authored by Claude Opus 5.5
parent 3a11c11543
commit e0621713d4
24 changed files with 150 additions and 17 deletions
+12
View File
@@ -28,6 +28,16 @@ class RuleDelivery(Base):
(`repeat`). Repeats are recorded too: they are deliveries a session can
open, and the case for retiring a rule rests on how rarely they are.
`plugin` is the version of the plugin that asked for the line, from the
request's `X-Grimoire-Plugin` header. Only a plugin that sends it reports
every open (`grimoire_record_opened.sh`), so a delivery without one was
made to a session whose opens never reach the server, and its unstamped
`opened_at` says nothing about whether it was read. The open-rate readers
count only deliveries that carry it. The server and the plugin ship on
different channels (the server from `dev`, the plugin from `main`, and a
running session keeps the plugin it started with), so rows from an older
plugin keep arriving for as long as such a session lives.
FK-free on `rule_id` and `user_id`, like the other telemetry tables: the
evidence that a rule was delivered forty times and opened never outlives
the rule, because it is the case for having deleted it.
@@ -46,6 +56,7 @@ class RuleDelivery(Base):
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
# Stamping an open: this session's latest delivery of this rule.
@@ -66,4 +77,5 @@ class RuleDelivery(Base):
"form": self.form,
"delivered_at": iso(self.delivered_at),
"opened_at": iso(self.opened_at),
"plugin": self.plugin,
}
+5 -2
View File
@@ -44,14 +44,17 @@ async def _bind_delivery_session() -> None:
A hook names it as `session_id` in the query, or carries it in the event
it posts (`/moment` sends the PreToolUse event whole). A request that
names none records no deliveries and reads no delivery history.
names none records no deliveries and reads no delivery history. The
plugin's version comes in the `X-Grimoire-Plugin` header and is kept on
each delivery, which is how the open-rate readers tell a session that
did not open a rule from one whose plugin never said.
"""
sid = request.args.get("session_id") or ""
if not sid and request.method == "POST":
body = await request.get_json(silent=True)
if isinstance(body, dict):
sid = str(body.get("session_id") or "")
rule_deliveries_svc.bind_session(sid)
rule_deliveries_svc.bind_session(sid, request.headers.get("X-Grimoire-Plugin"))
@plugin_bp.after_request
+18 -3
View File
@@ -13,6 +13,10 @@ Three calls, one table (`rule_deliveries`):
- `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.
"""
@@ -46,10 +50,17 @@ _UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
_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) -> 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([])
@@ -89,10 +100,12 @@ def record(
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}
"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
@@ -148,7 +161,8 @@ 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.
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:
@@ -164,6 +178,7 @@ async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float
.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)
@@ -46,7 +46,7 @@ from grimoire.models.rule_field_judgment import (
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.rule_usage import RuleUsageEvent
from grimoire.models.rulebook import Rule
from grimoire.services import lesson_rules, rule_order
from grimoire.services import lesson_rules, rule_deliveries, rule_order
from grimoire.services import rule_triggers as triggers_svc
from grimoire.services.rule_moment_judgments import _int, _mounts, _owned_rules as _owned
from grimoire.services.rulebooks import ENFORCEMENTS, SALIENCES
@@ -108,6 +108,8 @@ async def history(session, user_id: int, rule_ids) -> dict[int, dict]:
(`at`: a moment, or the arm that found it), busiest first; `pulled`,
`applied` and `departed` from the usage events; `misfire_days`, the days
sessions reported a mount of it arriving where it did not apply.
Deliveries count only when their plugin reports opens
(`rule_deliveries.REPORTS_OPENS`), so `opened` over `delivered` is a rate.
"""
ids = sorted({int(r) for r in rule_ids or []})
out = {rid: {"days": HISTORY_DAYS, "delivered": 0, "opened": 0, "places": [],
@@ -122,7 +124,7 @@ async def history(session, user_id: int, rule_ids) -> dict[int, dict]:
func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)),
)
.where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since,
RuleDelivery.rule_id.in_(ids))
rule_deliveries.REPORTS_OPENS, RuleDelivery.rule_id.in_(ids))
.group_by(RuleDelivery.rule_id, RuleDelivery.at)
)).all()
for rid, at, delivered, opened in rows: