feat(8118,8119): telemetry reads take a closed window, and every enter_project records whether it carried the family line
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / integration (push) Failing after 2m15s
CI & Build / Python tests (push) Successful in 2m23s
CI & Build / Build & push image (push) Skipped

#8119: retrieval_telemetry and list_rules(with_usage) take `since` and
`until` (ISO date or datetime) besides `days`. Every windowed count is
bounded at both ends: sources, note/rule/system/moment usage, record
reach, judged lines and the floor-moved check. A review read after its
period can now keep a later deploy out of its counts. A bad bound is
refused rather than widened.

#8118: enter_project writes one AppLog row (family / enter_project) per
entry: the project, whether the family line was shown, its counts, and
whether the readout failed. It is spawned, so the handshake does not wait.
retrieval_telemetry gains a `family_line` block: per project, entries,
entries that carried the line, first and last shown, and the latest
counts. Review #5132's "did the project's sessions see the line" is now
answerable from this deploy on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 00:01:19 -05:00
co-authored by Claude Opus 5.5
parent 0e946ffac8
commit 577a8e8621
12 changed files with 389 additions and 29 deletions
+8
View File
@@ -311,13 +311,21 @@ async def enter_project(project_id: int) -> dict:
out["systems_bootstrap"] = systems_bootstrap out["systems_bootstrap"] = systems_bootstrap
# Family canon: counts only, attached when one is # Family canon: counts only, attached when one is
# non-zero. A readout must never fail the handshake it rides on. # non-zero. A readout must never fail the handshake it rides on.
family_failed = False
try: try:
family = await family_adoption_svc.family_readout(uid, project_id) family = await family_adoption_svc.family_readout(uid, project_id)
except Exception: except Exception:
logger.warning("family readout failed for project %s", project_id, exc_info=True) logger.warning("family readout failed for project %s", project_id, exc_info=True)
family = None family = None
family_failed = True
if family: if family:
out["family"] = family out["family"] = family
# Every entry is recorded, with or without the line, so a later review
# can say whether a project's sessions saw what it owes
# (retrieval_telemetry's `family_line`). In the background, so the
# handshake never waits on its own telemetry.
spawn(family_adoption_svc.record_entry(uid, project_id, family, failed=family_failed),
site="family_entry_record")
if inception_ask: if inception_ask:
out["inception"] = inception_ask out["inception"] = inception_ask
# The core reply shape: for a client with no prompt hook, # The core reply shape: for a client with no prompt hook,
+22 -5
View File
@@ -208,7 +208,7 @@ def _rule_summary(r, moments: list[str] | None = None) -> dict:
async def list_rules( async def list_rules(
rulebook_id: int = 0, topic_id: int = 0, project_id: int = 0, rulebook_id: int = 0, topic_id: int = 0, project_id: int = 0,
with_usage: bool = False, days: int = 0, with_usage: bool = False, days: int = 0, since: str = "", until: str = "",
) -> dict: ) -> dict:
"""List rules — filter by rulebook, topic, and/or project. """List rules — filter by rulebook, topic, and/or project.
@@ -223,6 +223,11 @@ async def list_rules(
them. them.
days: with `with_usage`, count only the last N days; 0 = everything days: with `with_usage`, count only the last N days; 0 = everything
recorded. recorded.
since, until: with `with_usage`, count only events in [since, until),
each an ISO date or datetime (a bare `until` date covers that
whole day). They replace `days`. Use them for a review read after
its period, so a later deploy stays out of the counts. An
unparseable bound is refused with `error`.
rulebook_id and topic_id AND-combine; project_id lists a project's rules rulebook_id and topic_id AND-combine; project_id lists a project's rules
on its own. Ownership-scoped. on its own. Ownership-scoped.
@@ -235,6 +240,16 @@ async def list_rules(
ones that surface and get opened. ones that surface and get opened.
""" """
uid = current_user_id() uid = current_user_id()
window_since = window_until = None
if with_usage and (since or until):
from grimoire.services.retrieval_telemetry import resolve_window
try:
window_since, window_until = resolve_window(days or 30, since or None, until or None)
except ValueError as exc:
return {"error": str(exc)}
if not since and not days:
# An end with no start or count means everything up to that end.
window_since = None
rows = await rulebooks_svc.list_rules( rows = await rulebooks_svc.list_rules(
user_id=uid, user_id=uid,
rulebook_id=rulebook_id or None, rulebook_id=rulebook_id or None,
@@ -246,10 +261,12 @@ async def list_rules(
mounted = await rulebooks_svc.list_rule_moments(ids) mounted = await rulebooks_svc.list_rule_moments(ids)
rules = [_rule_summary(r, mounted.get(r.id)) for r in rows] rules = [_rule_summary(r, mounted.get(r.id)) for r in rows]
if with_usage: if with_usage:
since = ( if window_until is not None:
datetime.now(timezone.utc) - timedelta(days=days) if days > 0 else None usage = await usage_for_rules(ids, since=window_since, until=window_until)
) else:
usage = await usage_for_rules(ids, since=since) usage = await usage_for_rules(ids, since=(
datetime.now(timezone.utc) - timedelta(days=days) if days > 0 else None
))
lessons = await confirmed_lesson_counts(uid, ids) lessons = await confirmed_lesson_counts(uid, ids)
for row in rules: for row in rules:
row["usage"] = usage.get(row["id"], empty_rule_usage()) row["usage"] = usage.get(row["id"], empty_rule_usage())
+27 -2
View File
@@ -361,7 +361,7 @@ async def search(
async def retrieval_telemetry( async def retrieval_telemetry(
days: int = 30, near_miss_samples: int = 0, days: int = 30, near_miss_samples: int = 0, since: str = "", until: str = "",
) -> dict: ) -> dict:
"""What the retrieval telemetry says about YOUR surfaces, over a window. """What the retrieval telemetry says about YOUR surfaces, over a window.
@@ -659,16 +659,41 @@ async def retrieval_telemetry(
from an empty window, which would otherwise read as every counter at from an empty window, which would otherwise read as every counter at
zero. zero.
`family_line` — how often each project was entered and how often the
entry carried the family line, from the `enter_project` rows: per
project, `entries`, `entries_with_line`, the first and last time the line
was shown, and the counts it showed most recently. It answers "did this
project's sessions see the family canon it owes", which no other block
can.
A CLOSED WINDOW FOR A REVIEW READ LATE. `days` counts back from now, so
a review read two weeks after its period also counts whatever shipped
since. Pass `since` and `until` to fix both ends to the period under
review; the response's `since` and `until` name the window that was used.
Args: Args:
days: window size, default 30. Clamped to at least 1. days: window size, default 30. Clamped to at least 1. Ignored when
`since` is given.
near_miss_samples: 0-20, default 0. How many of each source's highest near_miss_samples: 0-20, default 0. How many of each source's highest
scoring DECLINES to list by record, with the query that asked. scoring DECLINES to list by record, with the query that asked.
Pass it when you are about to move a threshold; leave it off Pass it when you are about to move a threshold; leave it off
otherwise. See the near-miss section above for why a percentile otherwise. See the near-miss section above for why a percentile
alone cannot settle a bar. alone cannot settle a bar.
since: start of the window, an ISO date or datetime (UTC when no
zone is given). Empty = `days` before `until`.
until: end of the window, exclusive. A bare date covers that whole
day. Empty = now. An unparseable bound, or `since` not before
`until`, is refused with `error`.
""" """
from grimoire.services.retrieval_telemetry import resolve_window
try:
start, end = resolve_window(days, since or None, until or None)
except ValueError as exc:
return {"error": str(exc)}
return await retrieval_summary( return await retrieval_summary(
current_user_id(), days=days, near_miss_samples=near_miss_samples, current_user_id(), days=days, near_miss_samples=near_miss_samples,
since=start, until=end,
) )
+100
View File
@@ -1261,6 +1261,106 @@ async def family_readout(user_id: int, project_id: int) -> dict | None:
return family_line(project_id, matrix["cells"]) return family_line(project_id, matrix["cells"])
# --- whether the line reached the project ---------------------------------------
#
# One AppLog row per enter_project, whether or not it carried the line: the
# entries are the denominator, and without them "the line was shown 3 times"
# could not be told from "the project was entered 3 times and showed it
# every time". A failed readout is recorded as such, so it does not count as
# an entry that had nothing to show.
ENTRY_LOG_CATEGORY = "family"
ENTRY_LOG_ACTION = "enter_project"
async def record_entry(user_id: int, project_id: int, line: dict | None, *,
failed: bool = False) -> None:
"""Record one entry to a project and the family line it carried, if any.
Never raises: telemetry must not fail the handshake it describes."""
import json
from grimoire.models.app_log import AppLog
details = {"project_id": int(project_id), "shown": bool(line)}
if failed:
details["readout_failed"] = True
if line:
details.update({k: int(line.get(k) or 0) for k in ("unassessed", "owed", "needs_recheck")})
try:
async with async_session() as session:
session.add(AppLog(
category=ENTRY_LOG_CATEGORY, user_id=user_id, action=ENTRY_LOG_ACTION,
details=json.dumps(details),
))
await session.commit()
except Exception: # noqa: BLE001 - observation never breaks the observed
logger.debug("family line entry not recorded", exc_info=True)
async def entry_summary(user_id: int | None, since, until) -> dict:
"""Per project, over [since, until): how many times it was entered, how
many of those entries carried the family line, when the line was first
and last shown, and the counts it showed last. Projects ordered by
entries. Raises on a failed read; the caller guards it.
`complete_from` is the first entry row ever recorded. A window starting
before it holds no entry data, and that is no measurement, not "never
entered"."""
import json
from grimoire.models.app_log import AppLog
from grimoire.models.base import iso
where = (AppLog.category == ENTRY_LOG_CATEGORY, AppLog.action == ENTRY_LOG_ACTION,
AppLog.user_id == user_id)
async with async_session() as session:
rows = (await session.execute(
select(AppLog.details, AppLog.created_at)
.where(*where, AppLog.created_at >= since, AppLog.created_at < until)
.order_by(AppLog.created_at)
)).all()
first = (await session.execute(select(func.min(AppLog.created_at)).where(*where))).scalar()
titles = {}
ids = set()
parsed = []
for raw, at in rows:
try:
d = json.loads(raw or "{}")
pid = int(d["project_id"])
except (ValueError, KeyError, TypeError):
continue
ids.add(pid)
parsed.append((pid, d, at))
if ids:
titles = dict((await session.execute(
select(Project.id, Project.title).where(Project.id.in_(ids))
)).all())
projects: dict[int, dict] = {}
for pid, d, at in parsed:
slot = projects.setdefault(pid, {
"project_id": pid, "title": titles.get(pid), "entries": 0,
"entries_with_line": 0, "readout_failed": 0,
"first_shown_at": None, "last_shown_at": None, "last_counts": None,
})
slot["entries"] += 1
if d.get("readout_failed"):
slot["readout_failed"] += 1
if d.get("shown"):
slot["entries_with_line"] += 1
slot["first_shown_at"] = slot["first_shown_at"] or iso(at)
slot["last_shown_at"] = iso(at)
slot["last_counts"] = {k: int(d.get(k) or 0)
for k in ("unassessed", "owed", "needs_recheck")}
return {
"entries": sum(p["entries"] for p in projects.values()),
"entries_with_line": sum(p["entries_with_line"] for p in projects.values()),
"by_project": sorted(projects.values(), key=lambda p: (-p["entries"], p["project_id"])),
"complete_from": iso(first),
"covers_window": None if first is None else first <= since,
}
async def family_reach_ids(project_id: int, session=None) -> set[int]: async def family_reach_ids(project_id: int, session=None) -> set[int]:
"""The family records a project's retrieval reaches beyond its own: every """The family records a project's retrieval reaches beyond its own: every
canon idea on a platform the project is a member of, and each idea's canon idea on a platform the project is a member of, and each idea's
+12 -4
View File
@@ -235,8 +235,10 @@ async def mark_opened(user_id: int, session_id: str | None, note_id: int, plugin
return DIRECT return DIRECT
async def summary(user_id: int, days: int = 30) -> dict: async def summary(user_id: int, days: int = 30, *, since: datetime | None = None,
"""How records reached this user's sessions over the last `days`. until: datetime | None = None) -> dict:
"""How records reached this user's sessions over the last `days`, or over
[`since`, `until`) when the caller bounds the window itself.
Per kind: `delivered` and `opened` rows for each way a record arrived Per kind: `delivered` and `opened` rows for each way a record arrived
(`pushed` by a hook, `asked` through the session's own search, `direct` (`pushed` by a hook, `asked` through the session's own search, `direct`
@@ -244,8 +246,12 @@ async def summary(user_id: int, days: int = 30) -> dict:
row is always opened; it is counted so the readout shows how much a row is always opened; it is counted so the readout shows how much a
session reaches without being shown. session reaches without being shown.
""" """
days = max(1, min(int(days or 30), rule_deliveries.RETAIN_DAYS)) until = until or datetime.now(timezone.utc)
since = datetime.now(timezone.utc) - timedelta(days=days) if since is None:
days = max(1, min(int(days or 30), rule_deliveries.RETAIN_DAYS))
since = until - timedelta(days=days)
else:
days = round((until - since).total_seconds() / 86400, 2)
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( rows = (await session.execute(
select( select(
@@ -255,12 +261,14 @@ async def summary(user_id: int, days: int = 30) -> dict:
func.count(func.distinct(RecordDelivery.session_id)), func.count(func.distinct(RecordDelivery.session_id)),
) )
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since, .where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
RecordDelivery.delivered_at < until,
RecordDelivery.plugin.is_not(None)) RecordDelivery.plugin.is_not(None))
.group_by(RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source) .group_by(RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source)
)).all() )).all()
sessions = (await session.execute( sessions = (await session.execute(
select(func.count(func.distinct(RecordDelivery.session_id))) select(func.count(func.distinct(RecordDelivery.session_id)))
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since, .where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
RecordDelivery.delivered_at < until,
RecordDelivery.plugin.is_not(None)) RecordDelivery.plugin.is_not(None))
)).scalar_one() )).scalar_one()
+4 -2
View File
@@ -39,7 +39,7 @@ threshold with extra steps, which is the thing this exists to replace.
import logging import logging
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, exists, func, select from sqlalchemy import and_, exists, func, select, true
from grimoire.models import async_session from grimoire.models import async_session
from grimoire.models.base import iso from grimoire.models.base import iso
@@ -404,7 +404,7 @@ async def judge_menu(
} }
async def judged_block(user_id: int | None, since) -> dict: async def judged_block(user_id: int | None, since, until=None) -> dict:
"""`retrieval_telemetry`'s judged block: verdicts by rank, per source. """`retrieval_telemetry`'s judged block: verdicts by rank, per source.
Counts, not rates, beside each other per rank — the sample is small by Counts, not rates, beside each other per rank — the sample is small by
@@ -427,6 +427,7 @@ async def judged_block(user_id: int | None, since) -> dict:
.where( .where(
RetrievalJudgment.user_id == user_id, RetrievalJudgment.user_id == user_id,
RetrievalJudgment.created_at >= since, RetrievalJudgment.created_at >= since,
RetrievalJudgment.created_at < until if until is not None else true(),
) )
.group_by( .group_by(
RetrievalJudgment.source, RetrievalJudgment.rank, RetrievalJudgment.source, RetrievalJudgment.rank,
@@ -442,6 +443,7 @@ async def judged_block(user_id: int | None, since) -> dict:
.where( .where(
RetrievalJudgment.user_id == user_id, RetrievalJudgment.user_id == user_id,
RetrievalJudgment.created_at >= since, RetrievalJudgment.created_at >= since,
RetrievalJudgment.created_at < until if until is not None else true(),
) )
.group_by(RetrievalJudgment.source) .group_by(RetrievalJudgment.source)
)).all()) )).all())
+71 -9
View File
@@ -837,7 +837,7 @@ def _silent_surfaces(sources: dict, usage: dict, rule_usage: dict,
SYSTEM_USAGE_TOP = 20 SYSTEM_USAGE_TOP = 20
async def _system_usage(user_id: int | None, since) -> dict: async def _system_usage(user_id: int | None, since, until) -> dict:
"""The rulings arm's own block: were an area's rulings shown, and """The rulings arm's own block: were an area's rulings shown, and
was the area then opened. was the area then opened.
@@ -871,6 +871,7 @@ async def _system_usage(user_id: int | None, since) -> dict:
async with async_session() as session: async with async_session() as session:
where = ( where = (
SystemUsageEvent.created_at >= since, SystemUsageEvent.created_at >= since,
SystemUsageEvent.created_at < until,
SystemUsageEvent.user_id == user_id, SystemUsageEvent.user_id == user_id,
) )
per_source = ( per_source = (
@@ -943,7 +944,7 @@ async def _system_usage(user_id: int | None, since) -> dict:
async def moment_usage(user_id: int | None, since) -> dict: async def moment_usage(user_id: int | None, since, until=None) -> dict:
"""Deliveries and opens per moment. """Deliveries and opens per moment.
A mounted rule's delivery is a `moment_rule` surfacing whose `detail` is A mounted rule's delivery is a `moment_rule` surfacing whose `detail` is
@@ -973,6 +974,8 @@ async def moment_usage(user_id: int | None, since) -> dict:
""" """
from grimoire.services.retrieval_pipeline import MOMENT_RULE_SOURCE from grimoire.services.retrieval_pipeline import MOMENT_RULE_SOURCE
if until is None:
until = datetime.now(timezone.utc)
block: dict = {"by_moment": {}} block: dict = {"by_moment": {}}
try: try:
async with async_session() as session: async with async_session() as session:
@@ -986,6 +989,7 @@ async def moment_usage(user_id: int | None, since) -> dict:
) )
.where( .where(
RuleUsageEvent.created_at >= since, RuleUsageEvent.created_at >= since,
RuleUsageEvent.created_at < until,
RuleUsageEvent.user_id == user_id, RuleUsageEvent.user_id == user_id,
RuleUsageEvent.event == RULE_SURFACED, RuleUsageEvent.event == RULE_SURFACED,
RuleUsageEvent.source == MOMENT_RULE_SOURCE, RuleUsageEvent.source == MOMENT_RULE_SOURCE,
@@ -1002,6 +1006,7 @@ async def moment_usage(user_id: int | None, since) -> dict:
# autoescape: `_` is a LIKE wildcard (see the note block). # autoescape: `_` is a LIKE wildcard (see the note block).
pull.source.startswith("mcp_", autoescape=True), pull.source.startswith("mcp_", autoescape=True),
pull.created_at >= per_rule.c.first_at, pull.created_at >= per_rule.c.first_at,
pull.created_at < until,
) )
# One row per (moment, rule); the moment's totals are summed from # One row per (moment, rule); the moment's totals are summed from
# these below, so `by_rule` and the totals cannot disagree. # these below, so `by_rule` and the totals cannot disagree.
@@ -1049,8 +1054,40 @@ async def moment_usage(user_id: int | None, since) -> dict:
block.update(_coverage(complete.get("*"), since)) block.update(_coverage(complete.get("*"), since))
return block return block
def resolve_window(days: int = 30, since=None, until=None) -> tuple[datetime, datetime]:
"""The [since, until) window a telemetry read counts over.
`days` counts back from `until`, and `until` defaults to now. An explicit
`since` replaces the count. A review read after the period it describes
passes both bounds, so a deploy that landed after the period stays out of
the counts. `since` and `until` are aware datetimes, or ISO date/datetime
strings: a bare date as `until` covers the whole of that day. An
unparseable value is refused rather than silently widened to the default,
because a window the caller did not ask for reads exactly like the one
they did.
"""
from grimoire.services.logging import parse_filter_datetime
def _bound(value, *, end_of_day: bool):
if value is None or value == "":
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
parsed = parse_filter_datetime(str(value), end_of_day=end_of_day)
if parsed is None:
raise ValueError(f"not an ISO date or datetime: {value!r}")
return parsed
end = _bound(until, end_of_day=True) or datetime.now(timezone.utc)
start = _bound(since, end_of_day=False) or end - timedelta(days=max(1, int(days or 30)))
if start >= end:
raise ValueError(f"since ({start.isoformat()}) must be before until ({end.isoformat()})")
return start, end
async def retrieval_summary( async def retrieval_summary(
user_id: int | None, *, days: int = 30, near_miss_samples: int = 0, user_id: int | None, *, days: int = 30, near_miss_samples: int = 0,
since=None, until=None,
) -> dict: ) -> dict:
"""What the retrieval telemetry says, per surface, over a window. """What the retrieval telemetry says, per surface, over a window.
@@ -1080,10 +1117,11 @@ async def retrieval_summary(
no readout. It does distinguish "no rows" from "the read failed", because no readout. It does distinguish "no rows" from "the read failed", because
a read outage that looks like a quiet window can go unnoticed for weeks. a read outage that looks like a quiet window can go unnoticed for weeks.
""" """
since = datetime.now(timezone.utc) - timedelta(days=max(1, int(days))) since, until = resolve_window(days, since, until)
out: dict = { out: dict = {
"window_days": int(days), "window_days": round((until - since).total_seconds() / 86400, 2),
"since": iso(since), "since": iso(since),
"until": iso(until),
"sources": {}, "sources": {},
"usage": {}, "usage": {},
"rule_usage": {}, "rule_usage": {},
@@ -1181,6 +1219,7 @@ async def retrieval_summary(
) )
.where( .where(
RetrievalLog.created_at >= since, RetrievalLog.created_at >= since,
RetrievalLog.created_at < until,
RetrievalLog.user_id == user_id, RetrievalLog.user_id == user_id,
) )
.group_by(RetrievalLog.source) .group_by(RetrievalLog.source)
@@ -1239,6 +1278,7 @@ async def retrieval_summary(
.where( .where(
declined, declined,
RetrievalLog.created_at >= since, RetrievalLog.created_at >= since,
RetrievalLog.created_at < until,
RetrievalLog.user_id == user_id, RetrievalLog.user_id == user_id,
RetrievalLog.best_available_id.isnot(None), RetrievalLog.best_available_id.isnot(None),
) )
@@ -1282,6 +1322,7 @@ async def retrieval_summary(
) )
.where( .where(
NoteUsageEvent.created_at >= since, NoteUsageEvent.created_at >= since,
NoteUsageEvent.created_at < until,
NoteUsageEvent.user_id == user_id, NoteUsageEvent.user_id == user_id,
) )
.group_by(NoteUsageEvent.event, NoteUsageEvent.source) .group_by(NoteUsageEvent.event, NoteUsageEvent.source)
@@ -1300,6 +1341,7 @@ async def retrieval_summary(
await session.execute( await session.execute(
select(func.count(func.distinct(NoteUsageEvent.note_id))).where( select(func.count(func.distinct(NoteUsageEvent.note_id))).where(
NoteUsageEvent.created_at >= since, NoteUsageEvent.created_at >= since,
NoteUsageEvent.created_at < until,
NoteUsageEvent.user_id == user_id, NoteUsageEvent.user_id == user_id,
NoteUsageEvent.event == SURFACED, NoteUsageEvent.event == SURFACED,
NoteUsageEvent.source.notin_(_AMB), NoteUsageEvent.source.notin_(_AMB),
@@ -1310,6 +1352,7 @@ async def retrieval_summary(
await session.execute( await session.execute(
select(func.count(func.distinct(NoteUsageEvent.note_id))).where( select(func.count(func.distinct(NoteUsageEvent.note_id))).where(
NoteUsageEvent.created_at >= since, NoteUsageEvent.created_at >= since,
NoteUsageEvent.created_at < until,
NoteUsageEvent.user_id == user_id, NoteUsageEvent.user_id == user_id,
NoteUsageEvent.event == PULLED, NoteUsageEvent.event == PULLED,
) )
@@ -1341,6 +1384,7 @@ async def retrieval_summary(
select(NoteUsageEvent.note_id) select(NoteUsageEvent.note_id)
.where( .where(
NoteUsageEvent.created_at >= since, NoteUsageEvent.created_at >= since,
NoteUsageEvent.created_at < until,
NoteUsageEvent.user_id == user_id, NoteUsageEvent.user_id == user_id,
NoteUsageEvent.event == PULLED, NoteUsageEvent.event == PULLED,
# autoescape because `_` is a LIKE wildcard: a bare # autoescape because `_` is a LIKE wildcard: a bare
@@ -1356,6 +1400,7 @@ async def retrieval_summary(
select(NoteUsageEvent.source, NoteUsageEvent.note_id) select(NoteUsageEvent.source, NoteUsageEvent.note_id)
.where( .where(
NoteUsageEvent.created_at >= since, NoteUsageEvent.created_at >= since,
NoteUsageEvent.created_at < until,
NoteUsageEvent.user_id == user_id, NoteUsageEvent.user_id == user_id,
NoteUsageEvent.event == SURFACED, NoteUsageEvent.event == SURFACED,
) )
@@ -1409,6 +1454,7 @@ async def retrieval_summary(
) )
.where( .where(
RuleUsageEvent.created_at >= since, RuleUsageEvent.created_at >= since,
RuleUsageEvent.created_at < until,
RuleUsageEvent.user_id == user_id, RuleUsageEvent.user_id == user_id,
) )
.group_by(RuleUsageEvent.event, RuleUsageEvent.source) .group_by(RuleUsageEvent.event, RuleUsageEvent.source)
@@ -1431,6 +1477,7 @@ async def retrieval_summary(
select(func.count(func.distinct(RuleUsageEvent.rule_id))) select(func.count(func.distinct(RuleUsageEvent.rule_id)))
.where( .where(
RuleUsageEvent.created_at >= since, RuleUsageEvent.created_at >= since,
RuleUsageEvent.created_at < until,
RuleUsageEvent.user_id == user_id, RuleUsageEvent.user_id == user_id,
RuleUsageEvent.event == RULE_SURFACED, RuleUsageEvent.event == RULE_SURFACED,
) )
@@ -1441,6 +1488,7 @@ async def retrieval_summary(
select(func.count(func.distinct(RuleUsageEvent.rule_id))) select(func.count(func.distinct(RuleUsageEvent.rule_id)))
.where( .where(
RuleUsageEvent.created_at >= since, RuleUsageEvent.created_at >= since,
RuleUsageEvent.created_at < until,
RuleUsageEvent.user_id == user_id, RuleUsageEvent.user_id == user_id,
RuleUsageEvent.event == RULE_PULLED, RuleUsageEvent.event == RULE_PULLED,
) )
@@ -1456,6 +1504,7 @@ async def retrieval_summary(
select(func.count(func.distinct(RuleUsageEvent.rule_id))) select(func.count(func.distinct(RuleUsageEvent.rule_id)))
.where( .where(
RuleUsageEvent.created_at >= since, RuleUsageEvent.created_at >= since,
RuleUsageEvent.created_at < until,
RuleUsageEvent.user_id == user_id, RuleUsageEvent.user_id == user_id,
RuleUsageEvent.event.in_(RULE_OUTCOMES), RuleUsageEvent.event.in_(RULE_OUTCOMES),
) )
@@ -1477,6 +1526,7 @@ async def retrieval_summary(
select(RuleUsageEvent.rule_id) select(RuleUsageEvent.rule_id)
.where( .where(
RuleUsageEvent.created_at >= since, RuleUsageEvent.created_at >= since,
RuleUsageEvent.created_at < until,
RuleUsageEvent.user_id == user_id, RuleUsageEvent.user_id == user_id,
RuleUsageEvent.event == RULE_PULLED, RuleUsageEvent.event == RULE_PULLED,
RuleUsageEvent.source.startswith("mcp_", autoescape=True), RuleUsageEvent.source.startswith("mcp_", autoescape=True),
@@ -1488,6 +1538,7 @@ async def retrieval_summary(
select(RuleUsageEvent.source, RuleUsageEvent.rule_id) select(RuleUsageEvent.source, RuleUsageEvent.rule_id)
.where( .where(
RuleUsageEvent.created_at >= since, RuleUsageEvent.created_at >= since,
RuleUsageEvent.created_at < until,
RuleUsageEvent.user_id == user_id, RuleUsageEvent.user_id == user_id,
RuleUsageEvent.event == RULE_SURFACED, RuleUsageEvent.event == RULE_SURFACED,
) )
@@ -1716,14 +1767,14 @@ async def retrieval_summary(
} }
rule_usage.update(_coverage((rule_complete or {}).get("*"), since)) rule_usage.update(_coverage((rule_complete or {}).get("*"), since))
out["rule_usage"] = rule_usage out["rule_usage"] = rule_usage
out["system_usage"] = await _system_usage(user_id, since) out["system_usage"] = await _system_usage(user_id, since, until)
out["moment_usage"] = await moment_usage(user_id, since) out["moment_usage"] = await moment_usage(user_id, since, until)
# How each non-rule record reached a session: pushed by a hook, returned # How each non-rule record reached a session: pushed by a hook, returned
# by a search the session ran, or opened with nothing delivering it — and # by a search the session ran, or opened with nothing delivering it — and
# how many were opened each way. Its own guard, so a failure flags itself. # how many were opened each way. Its own guard, so a failure flags itself.
try: try:
from grimoire.services import record_deliveries from grimoire.services import record_deliveries
out["record_reach"] = (await record_deliveries.summary(user_id, days=days) out["record_reach"] = (await record_deliveries.summary(user_id, since=since, until=until)
if user_id else None) if user_id else None)
except Exception: except Exception:
logger.exception("record reach read failed") logger.exception("record reach read failed")
@@ -1737,11 +1788,22 @@ async def retrieval_summary(
# `_system_usage`'s reason — a failure flags itself rather than printing # `_system_usage`'s reason — a failure flags itself rather than printing
# an empty block, which reads as "nothing judged". # an empty block, which reads as "nothing judged".
try: try:
out["judged"] = await judged_block(user_id, since) out["judged"] = await judged_block(user_id, since, until)
except Exception: except Exception:
logger.warning("judged block read failed", exc_info=True) logger.warning("judged block read failed", exc_info=True)
out["judged"] = {"judged_failed": True} out["judged"] = {"judged_failed": True}
# ── The family line ──────────────────────────────────────────────────
#
# How often each project was entered, and how often the entry carried
# the family line. Its own guard, for the judged block's reason.
try:
from grimoire.services.family_adoption import entry_summary
out["family_line"] = await entry_summary(user_id, since, until)
except Exception:
logger.warning("family line read failed", exc_info=True)
out["family_line"] = {"family_line_failed": True}
# ── What is wrong ──────────────────────────────────────────────────── # ── What is wrong ────────────────────────────────────────────────────
# #
# Computed LAST, over the blocks above rather than over the database, so # Computed LAST, over the blocks above rather than over the database, so
@@ -1791,7 +1853,7 @@ async def retrieval_summary(
# account. # account.
floor_moves: dict[str, str] = {} floor_moves: dict[str, str] = {}
try: try:
floor_moves = await floor_moves_since(since) floor_moves = await floor_moves_since(since, until)
except Exception: # pragma: no cover - telemetry never raises except Exception: # pragma: no cover - telemetry never raises
logger.warning("could not read floor changes", exc_info=True) logger.warning("could not read floor changes", exc_info=True)
+5 -3
View File
@@ -34,7 +34,7 @@ from __future__ import annotations
import logging import logging
from sqlalchemy import func, or_, select from sqlalchemy import func, or_, select, true
from grimoire.models import async_session from grimoire.models import async_session
from grimoire.models.retrieval_tuning import RetrievalTuningEvent from grimoire.models.retrieval_tuning import RetrievalTuningEvent
@@ -389,8 +389,9 @@ async def record_release_defaults() -> list[dict]:
return written return written
async def floor_moves_since(since) -> dict[str, str]: async def floor_moves_since(since, until=None) -> dict[str, str]:
"""Surfaces whose floor genuinely MOVED at or after `since`. """Surfaces whose floor genuinely MOVED at or after `since` (and before
`until`, when given).
Genuinely: `old_value IS NOT NULL`, so a baseline row — which records a Genuinely: `old_value IS NOT NULL`, so a baseline row — which records a
default without changing it — does not read as a change. Returns surface -> default without changing it — does not read as a change. Returns surface ->
@@ -410,6 +411,7 @@ async def floor_moves_since(since) -> dict[str, str]:
RetrievalTuningEvent.dial == "floor", RetrievalTuningEvent.dial == "floor",
RetrievalTuningEvent.old_value.isnot(None), RetrievalTuningEvent.old_value.isnot(None),
RetrievalTuningEvent.created_at >= since, RetrievalTuningEvent.created_at >= since,
RetrievalTuningEvent.created_at < until if until is not None else true(),
) )
.order_by(RetrievalTuningEvent.created_at.desc()) .order_by(RetrievalTuningEvent.created_at.desc())
) )
+8 -2
View File
@@ -336,6 +336,7 @@ def empty_rule_usage() -> dict:
async def usage_for_rules( async def usage_for_rules(
rule_ids: list[int], since: datetime | None = None, rule_ids: list[int], since: datetime | None = None,
until: datetime | None = None,
) -> dict[int, dict]: ) -> dict[int, dict]:
"""Aggregate usage for a set of rules: {rule_id: {counts + timestamps}}. """Aggregate usage for a set of rules: {rule_id: {counts + timestamps}}.
@@ -344,8 +345,9 @@ async def usage_for_rules(
events come back with `empty_rule_usage()`, so the caller never has to tell events come back with `empty_rule_usage()`, so the caller never has to tell
"no events" from "not in the result". "no events" from "not in the result".
`since` limits the counts to events at or after it, so two windows can be `since` limits the counts to events at or after it, and `until` to events
compared; without it they cover everything recorded. before it, so two windows can be compared; without them the counts cover
everything recorded.
""" """
ids = [int(r) for r in rule_ids] ids = [int(r) for r in rule_ids]
out: dict[int, dict] = {rid: empty_rule_usage() for rid in ids} out: dict[int, dict] = {rid: empty_rule_usage() for rid in ids}
@@ -380,6 +382,10 @@ async def usage_for_rules(
RuleUsageEvent.created_at >= since RuleUsageEvent.created_at >= since
if since is not None else true() if since is not None else true()
) )
.where(
RuleUsageEvent.created_at < until
if until is not None else true()
)
.group_by( .group_by(
RuleUsageEvent.rule_id, RuleUsageEvent.rule_id,
RuleUsageEvent.event, RuleUsageEvent.event,
+37 -2
View File
@@ -356,8 +356,43 @@ async def test_enter_project_fires_the_coverage_seed_on_the_owner(
)) ))
await enter_project(project_id=5) await enter_project(project_id=5)
seed.assert_called_once_with(42, 5, cached=None) seed.assert_called_once_with(42, 5, cached=None)
_no_background_seed.assert_called_once() sites = [c.kwargs["site"] for c in _no_background_seed.call_args_list]
assert _no_background_seed.call_args.kwargs["site"] == "enter_project.coverage_seed" assert sites.count("enter_project.coverage_seed") == 1
@pytest.mark.asyncio
async def test_every_enter_records_whether_it_carried_the_family_line(
_no_family, _no_background_seed,
):
"""Review #5132 asks whether a project's sessions saw the family line.
Each enter records one entry, with the line or without it (the entries
are the denominator), and a failed readout is recorded as failed rather
than as an entry with nothing to show."""
import contextlib
line = {"line": "family canon…", "unassessed": 2, "owed": 1, "needs_recheck": 0}
async def enter():
with contextlib.ExitStack() as stack:
for cm in _enter_project_stubs(fake_project(id=5)):
stack.enter_context(cm)
record = stack.enter_context(patch(
"grimoire.mcp.tools.projects.family_adoption_svc.record_entry",
MagicMock(return_value=object()),
))
await enter_project(project_id=5)
sites = [c.kwargs["site"] for c in _no_background_seed.call_args_list]
assert "family_entry_record" in sites
return record
record = await enter()
record.assert_called_once_with(7, 5, None, failed=False)
_no_family.return_value = line
record = await enter()
record.assert_called_once_with(7, 5, line, failed=False)
_no_family.side_effect = RuntimeError("database down")
record = await enter()
record.assert_called_once_with(7, 5, None, failed=True)
@pytest.mark.asyncio @pytest.mark.asyncio
+26
View File
@@ -606,3 +606,29 @@ async def test_list_rules_carries_usage_only_when_asked():
assert usage.await_args.args[0] == [1, 2] assert usage.await_args.args[0] == [1, 2]
assert usage.await_args.kwargs["since"] is not None assert usage.await_args.kwargs["since"] is not None
lessons.assert_awaited_once_with(7, [1, 2]) lessons.assert_awaited_once_with(7, [1, 2])
@pytest.mark.asyncio
async def test_list_rules_counts_a_closed_window_when_a_review_names_one():
"""A review read after its period passes both ends, so a later deploy
stays out of the counts. A bare `until` date covers that whole day, and
an unparseable bound is refused rather than widened to the default."""
from datetime import datetime, timezone
from grimoire.mcp.tools import rulebooks as tools
usage = AsyncMock(return_value={})
with patch.object(tools.rulebooks_svc, "list_rules", AsyncMock(return_value=[fake_rule(id=1)])), \
patch.object(tools.rulebooks_svc, "list_rule_moments", AsyncMock(return_value={})), \
patch.object(tools, "usage_for_rules", usage), \
patch.object(tools, "confirmed_lesson_counts", AsyncMock(return_value={})):
await tools.list_rules(with_usage=True, since="2026-10-23", until="2026-11-24")
kw = usage.await_args.kwargs
assert kw["since"] == datetime(2026, 10, 23, tzinfo=timezone.utc)
assert kw["until"].date().isoformat() == "2026-11-24"
assert kw["until"] > datetime(2026, 11, 24, 23, 0, tzinfo=timezone.utc)
refused = await tools.list_rules(with_usage=True, since="last tuesday")
assert "error" in refused
backwards = await tools.list_rules(with_usage=True, since="2026-11-24", until="2026-10-23")
assert "error" in backwards
@@ -247,6 +247,75 @@ async def test_retrieval_summary_reads_what_the_writer_wrote(_dispose_engine):
await s.commit() await s.commit()
@pytest.mark.integration
@pytest.mark.asyncio
async def test_a_closed_window_leaves_out_what_came_after_it(_dispose_engine):
"""A review read late passes `until`, so events after the period under
review (a later deploy's traffic) are not counted. One surfacing inside
the window and one after it: only the first is counted, and the response
names the window it used."""
from datetime import datetime, timedelta, timezone
from sqlalchemy import delete
from grimoire.models import async_session
from grimoire.models.note_usage import NoteUsageEvent
from grimoire.services.retrieval_telemetry import retrieval_summary
UID = 990006
now = datetime.now(timezone.utc)
inside, after = now - timedelta(days=10), now - timedelta(days=2)
async with async_session() as s:
s.add_all([
NoteUsageEvent(user_id=UID, note_id=1, event="surfaced", source="auto_inject",
created_at=inside),
NoteUsageEvent(user_id=UID, note_id=2, event="surfaced", source="auto_inject",
created_at=after),
])
await s.commit()
try:
bounded = await retrieval_summary(UID, since=now - timedelta(days=14),
until=now - timedelta(days=5))
assert bounded["usage"]["surfaced"] == 1
assert bounded["until"] is not None and bounded["window_days"] == pytest.approx(9)
assert (await retrieval_summary(UID, days=14))["usage"]["surfaced"] == 2
finally:
async with async_session() as s:
await s.execute(delete(NoteUsageEvent).where(NoteUsageEvent.user_id == UID))
await s.commit()
@pytest.mark.integration
@pytest.mark.asyncio
async def test_family_line_counts_entries_and_the_ones_that_carried_the_line(_dispose_engine):
"""Review #5132's question: did a project's sessions see the family line?
Three entries to one project, two carrying the line; the readout counts
the entries as the denominator and keeps the latest counts shown."""
from sqlalchemy import delete
from grimoire.models import async_session
from grimoire.models.app_log import AppLog
from grimoire.services.family_adoption import record_entry
from grimoire.services.retrieval_telemetry import retrieval_summary
UID, PID = 990007, 990107
await record_entry(UID, PID, {"unassessed": 3, "owed": 1, "needs_recheck": 0})
await record_entry(UID, PID, None)
await record_entry(UID, PID, {"unassessed": 2, "owed": 1, "needs_recheck": 0})
try:
block = (await retrieval_summary(UID, days=1))["family_line"]
assert "family_line_failed" not in block
assert block["entries"] == 3 and block["entries_with_line"] == 2
(row,) = block["by_project"]
assert row["project_id"] == PID and row["readout_failed"] == 0
assert row["last_counts"] == {"unassessed": 2, "owed": 1, "needs_recheck": 0}
assert row["first_shown_at"] <= row["last_shown_at"]
finally:
async with async_session() as s:
await s.execute(delete(AppLog).where(AppLog.user_id == UID))
await s.commit()
@pytest.mark.integration @pytest.mark.integration
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_retrieval_summary_is_empty_not_broken_for_a_fresh_install(_dispose_engine): async def test_retrieval_summary_is_empty_not_broken_for_a_fresh_install(_dispose_engine):