feat(7831): every record a session is shown, asks for or opens on its own is recorded per session, by kind
CI & Build / Plugin hooks (push) Successful in 18s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 2m6s
CI & Build / Build & push image (push) Successful in 32s
CI & Build / Plugin hooks (push) Successful in 18s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 2m6s
CI & Build / Build & push image (push) Successful in 32s
A ledger beside the rule deliveries (record_deliveries, migration 0136): - every note, snippet, issue, lesson or process line a plugin door pushes is recorded against the session, only when the payload kept it; - a search the session runs itself records its results as asked, matched to the server log of that call; - an open is stamped on the delivery it followed, or recorded as direct when nothing showed the record first. The plugin reports opens and searches from the tool calls (grimoire_record_read.sh). The readout is in retrieval_telemetry (record_reach), at /api/retrieval/record-reach, and in Settings > Moments as "How records reach the work". Plugin 2026.11.24.1827. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -528,6 +528,15 @@ async def retrieval_telemetry(
|
||||
a ratio of opens would read near zero on an arm that is working.
|
||||
`system_usage_failed: true` means its read broke and the zeros mean nothing.
|
||||
|
||||
`record_reach` — how every non-rule record reached a session, from
|
||||
`record_deliveries`: per kind (`snippet`, `note`, `lesson`, `task:issue`,
|
||||
…), each way it arrived — `pushed` by a hook, `asked` (a result of a
|
||||
`search` the session ran itself), `direct` (opened with nothing
|
||||
delivering it first) — with `delivered` and `opened`, and per door in
|
||||
`sources`. It is the readout that says whether a kind is found by being
|
||||
pushed or by being asked for, which `usage` cannot: a pull there does not
|
||||
say which door led to it. Counts only sessions whose plugin reports opens.
|
||||
|
||||
`judged` — whether the lines RELATED, from `retrieval_judgments`:
|
||||
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
|
||||
on a sample of logged menus, `within_budget` against `beyond_budget` and
|
||||
|
||||
@@ -62,6 +62,7 @@ from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401
|
||||
from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
|
||||
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
|
||||
from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401
|
||||
from grimoire.models.record_delivery import RecordDelivery # noqa: E402, F401
|
||||
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
|
||||
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
|
||||
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, Index, Text, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from grimoire.models import Base
|
||||
from grimoire.models.base import iso
|
||||
|
||||
# How a record came to be in front of the session.
|
||||
PUSHED = "pushed" # a hook put it there unasked (auto-inject, the write path, a slot)
|
||||
ASKED = "asked" # it was a result of a search the session ran itself
|
||||
DIRECT = "direct" # it was opened with nothing delivering it first in the session
|
||||
WAYS = (PUSHED, ASKED, DIRECT)
|
||||
|
||||
|
||||
class RecordDelivery(Base):
|
||||
"""One record put in front of one session, and whether it was opened.
|
||||
|
||||
The note-side twin of `rule_deliveries`, for every record kind that is not
|
||||
a rule (note, snippet, issue, work task, lesson, process). It answers what
|
||||
`note_usage_events` cannot: a pull there does not say which door led to
|
||||
it, so "was this note opened because a hook pushed it, because the session
|
||||
searched for it, or because the session went to it on its own" has no
|
||||
answer. Here each line is a row against its session, and the open is
|
||||
stamped on the row it followed.
|
||||
|
||||
`way` says how the record arrived (`pushed`, `asked`, `direct`). `source`
|
||||
is the door: the hook arm (`auto_inject`, `write_path_semantic`,
|
||||
`write_path_place`, `lesson_slot`, …), `mcp_search` for a search the
|
||||
session ran, or `direct`. `kind` is the record's kind when it was
|
||||
delivered (`snippet`, `note`, `lesson`, `process`, `task:issue`,
|
||||
`task:work`, …), kept on the row so the readout needs no join and survives
|
||||
the record's deletion.
|
||||
|
||||
A `direct` row is written when a session opens a record that nothing
|
||||
delivered to it within the open window — found through a cross-reference,
|
||||
a task's own id, the operator naming it. It is delivered and opened at the
|
||||
same instant, and it is the measure of records a session reaches without
|
||||
being shown them.
|
||||
|
||||
FK-free on `note_id` and `user_id`, like the other telemetry tables, and
|
||||
pruned after `rule_deliveries.RETAIN_DAYS`.
|
||||
"""
|
||||
|
||||
__tablename__ = "record_deliveries"
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
session_id: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
note_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
kind: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
way: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
delivered_at: Mapped[datetime] = mapped_column(
|
||||
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 record.
|
||||
Index("ix_record_deliveries_session_note", "user_id", "session_id", "note_id", "delivered_at"),
|
||||
Index("ix_record_deliveries_delivered_at", "delivered_at"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"user_id": self.user_id,
|
||||
"session_id": self.session_id,
|
||||
"note_id": self.note_id,
|
||||
"kind": self.kind,
|
||||
"way": self.way,
|
||||
"source": self.source,
|
||||
"delivered_at": iso(self.delivered_at),
|
||||
"opened_at": iso(self.opened_at),
|
||||
"plugin": self.plugin,
|
||||
}
|
||||
@@ -22,6 +22,7 @@ from grimoire.services import reply_shapes as reply_shapes_svc
|
||||
from grimoire.services import repo_bindings as repo_bindings_svc
|
||||
from grimoire.services import rule_adherence as rule_adherence_svc
|
||||
from grimoire.services import report_check as report_check_svc
|
||||
from grimoire.services import record_deliveries as record_deliveries_svc
|
||||
from grimoire.services import rule_deliveries as rule_deliveries_svc
|
||||
from grimoire.services import rule_moment_judgments as judgments_svc
|
||||
from grimoire.services import shape_check as shape_check_svc
|
||||
@@ -60,12 +61,14 @@ async def _bind_delivery_session() -> None:
|
||||
|
||||
@plugin_bp.after_request
|
||||
async def _flush_deliveries(response):
|
||||
"""Write any rule deliveries a door rendered without fitting a payload.
|
||||
"""Write any rule and record deliveries a door rendered without fitting a
|
||||
payload.
|
||||
|
||||
A door that fits its payload (`hook_payload.fit`) has already written the
|
||||
lines it kept and dropped the rest, so this finds nothing left for it.
|
||||
"""
|
||||
rule_deliveries_svc.flush()
|
||||
record_deliveries_svc.flush()
|
||||
return response
|
||||
|
||||
|
||||
@@ -459,6 +462,53 @@ async def rule_opened():
|
||||
))
|
||||
|
||||
|
||||
@plugin_bp.post("/record-opened")
|
||||
@login_required
|
||||
async def record_opened():
|
||||
"""A session opened a record (a note, snippet, task, lesson or process).
|
||||
|
||||
Body: `{"session_id", "note_id"}`, posted by the plugin after a `get_note`,
|
||||
`get_task`, `get_snippet`, `get_lesson` or `get_process` call. The open is
|
||||
stamped on this session's latest delivery of the record; with none, it
|
||||
is recorded as `direct`, a record reached without being shown. Answers
|
||||
`{"way"}`: how the open was counted, or "" when it was not.
|
||||
"""
|
||||
data = await request.get_json(silent=True) or {}
|
||||
if not isinstance(data, dict):
|
||||
return jsonify({"way": ""})
|
||||
try:
|
||||
note_id = int(data.get("note_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
note_id = 0
|
||||
if note_id <= 0:
|
||||
return jsonify({"way": ""})
|
||||
way = await record_deliveries_svc.mark_opened(
|
||||
g.user.id, str(data.get("session_id") or ""), note_id,
|
||||
plugin=rule_deliveries_svc.current_plugin(),
|
||||
)
|
||||
return jsonify({"way": way})
|
||||
|
||||
|
||||
@plugin_bp.post("/record-searched")
|
||||
@login_required
|
||||
async def record_searched():
|
||||
"""A session ran `search` itself.
|
||||
|
||||
Body: `{"session_id", "q"}`, posted by the plugin after the call. The
|
||||
results that call returned, read from the server's own log of it, are
|
||||
recorded against the session as `asked`, so an open that follows counts
|
||||
as one the session reached by asking. Answers `{"recorded"}`.
|
||||
"""
|
||||
data = await request.get_json(silent=True) or {}
|
||||
if not isinstance(data, dict):
|
||||
return jsonify({"recorded": 0})
|
||||
recorded = await record_deliveries_svc.from_search(
|
||||
g.user.id, str(data.get("session_id") or ""), str(data.get("q") or ""),
|
||||
plugin=rule_deliveries_svc.current_plugin(),
|
||||
)
|
||||
return jsonify({"recorded": recorded})
|
||||
|
||||
|
||||
@plugin_bp.post("/rule-verdict")
|
||||
@login_required
|
||||
async def rule_verdict():
|
||||
|
||||
@@ -21,6 +21,7 @@ from grimoire.auth import get_current_user_id, login_required
|
||||
from grimoire.services import moment_actions as moment_actions_svc
|
||||
from grimoire.services import moments as moments_svc
|
||||
from grimoire.services import reply_shapes as shapes_svc
|
||||
from grimoire.services import record_deliveries as record_deliveries_svc
|
||||
from grimoire.services import rule_adherence as adherence_svc
|
||||
from grimoire.services import rule_field_judgments as weights_svc
|
||||
from grimoire.services import rule_moment_judgments as judgments_svc
|
||||
@@ -258,6 +259,19 @@ async def adherence_route():
|
||||
))
|
||||
|
||||
|
||||
@retrieval_bp.route("/record-reach", methods=["GET"])
|
||||
@login_required
|
||||
async def record_reach_route():
|
||||
"""How non-rule records reached this user's sessions: per kind, pushed by
|
||||
a hook, returned by the session's own search, or opened directly, and how
|
||||
many were opened each way. `?days=` sets the window (default 30)."""
|
||||
try:
|
||||
days = int(request.args.get("days") or 30)
|
||||
except ValueError:
|
||||
return jsonify({"error": "days must be a whole number"}), 400
|
||||
return jsonify(await record_deliveries_svc.summary(get_current_user_id(), days=days))
|
||||
|
||||
|
||||
@retrieval_bp.route("/weights/proposals", methods=["GET"])
|
||||
@login_required
|
||||
async def weight_proposals_route():
|
||||
|
||||
@@ -199,6 +199,8 @@ _NOT_INCLUDED = [
|
||||
# Adherence verdicts on those deliveries, keyed by the same session ids
|
||||
# and pruned with them.
|
||||
"rule_adherence",
|
||||
# The same per-session ledger for every other record kind.
|
||||
"record_deliveries",
|
||||
# Verdicts on retrieval_logs rows, so they go where their subject
|
||||
# goes: a restore that carried a judgment of a call it did not carry would
|
||||
# leave a verdict on nothing. A sample, re-takeable by the review pass.
|
||||
|
||||
@@ -120,11 +120,13 @@ def assemble(parts, budget: int) -> Fitted:
|
||||
|
||||
|
||||
async def fit(user_id: int, parts) -> Fitted:
|
||||
"""Assemble under this user's budget and record the rule lines delivered."""
|
||||
from grimoire.services import rule_deliveries
|
||||
"""Assemble under this user's budget and record the rule and record lines
|
||||
delivered."""
|
||||
from grimoire.services import record_deliveries, rule_deliveries
|
||||
|
||||
fitted = assemble(list(parts), await payload_budget(user_id))
|
||||
rule_deliveries.flush(set(fitted.ids(RULE)))
|
||||
record_deliveries.flush(set(fitted.ids(NOTE)))
|
||||
return fitted
|
||||
|
||||
|
||||
|
||||
@@ -136,6 +136,15 @@ def record_surfaced(
|
||||
logger.debug("note usage payload build failed", exc_info=True)
|
||||
return
|
||||
_schedule(rows)
|
||||
# The same lines, against the session a plugin door is delivering to. A
|
||||
# synced skill is not a line in front of the session, so it is left out.
|
||||
if source not in _NOT_A_LINE:
|
||||
from grimoire.services import record_deliveries
|
||||
record_deliveries.record(user_id, note_ids, source)
|
||||
|
||||
|
||||
# Surfacing sources that put nothing in front of the session as a line.
|
||||
_NOT_A_LINE = frozenset({"process_skill_sync"})
|
||||
|
||||
|
||||
def record_pulled(
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""Each non-rule record put in front of a session, how it got there, and
|
||||
whether the session opened it.
|
||||
|
||||
One table (`record_deliveries`), the note-side twin of `rule_deliveries`, and
|
||||
four calls:
|
||||
|
||||
- `record` — from `note_usage.record_surfaced`, every record a plugin door
|
||||
pushed to a bound session. Within a request the rows wait until the door's
|
||||
payload is fitted, and `flush` writes only those whose line made it in
|
||||
(`hook_payload.fit`), exactly as rule lines are kept.
|
||||
- `from_search` — the session ran `search` itself; the plugin reports it and
|
||||
the results that call returned are recorded as `asked`.
|
||||
- `mark_opened` — the session opened a record. The latest unopened delivery
|
||||
of it in the session gets the stamp. With nothing delivering it first, a
|
||||
`direct` row is written, delivered and opened at once: the record was
|
||||
reached without being shown.
|
||||
- `summary` — per kind, how records arrived (`pushed`, `asked`, `direct`),
|
||||
by door, and how many were opened.
|
||||
|
||||
Only rows from a plugin that reports its version count in the readout: an
|
||||
older plugin does not report opens, so its rows would read as never opened.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextvars import ContextVar
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import case, delete, func, select, tuple_, update
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.note import Note
|
||||
from grimoire.models.record_delivery import ASKED, DIRECT, PUSHED, RecordDelivery
|
||||
from grimoire.models.retrieval_log import RetrievalLog
|
||||
from grimoire.services import rule_deliveries
|
||||
from grimoire.services.access import readable_notes_clause
|
||||
from grimoire.services.background import spawn
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# A search the plugin reports is matched to the call the server logged within
|
||||
# this long before; the report follows the call by a second or two, so a
|
||||
# longer window only adds the chance of matching an older identical query.
|
||||
SEARCH_MATCH_WINDOW = timedelta(minutes=3)
|
||||
SEARCH_SOURCE = "mcp_search"
|
||||
DIRECT_SOURCE = "direct"
|
||||
|
||||
# Rows a bound request rendered, written by `flush`. Reset per request by
|
||||
# `rule_deliveries.bind_session`, so the two ledgers share one binding.
|
||||
_pending: ContextVar[list | None] = ContextVar("record_delivery_pending", default=None)
|
||||
|
||||
|
||||
def reset() -> None:
|
||||
_pending.set([])
|
||||
|
||||
|
||||
def record(user_id: int | None, note_ids, source: str) -> None:
|
||||
"""Record records a hook pushed to the bound session. A no-op outside a
|
||||
plugin request, since an open could never be tied back to it."""
|
||||
sid = rule_deliveries.current_session()
|
||||
if not sid or not user_id:
|
||||
return
|
||||
try:
|
||||
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": int(n),
|
||||
"way": PUSHED, "source": source, "plugin": rule_deliveries.current_plugin()}
|
||||
for n in dict.fromkeys(note_ids or [])]
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
logger.debug("record delivery payload build failed", exc_info=True)
|
||||
return
|
||||
pending = _pending.get()
|
||||
if pending is not None:
|
||||
pending.extend(rows)
|
||||
elif rows:
|
||||
spawn(_insert(rows), site="record_delivery_write")
|
||||
|
||||
|
||||
def flush(kept: set[int] | None = None) -> None:
|
||||
"""Write this request's buffered rows: those for records in `kept`, or all
|
||||
of them when `kept` is None. A record whose line the payload left out was
|
||||
never shown, so its row is dropped."""
|
||||
rows = _pending.get()
|
||||
if not rows:
|
||||
return
|
||||
_pending.set([])
|
||||
if kept is not None:
|
||||
rows = [r for r in rows if r["note_id"] in kept]
|
||||
if rows:
|
||||
spawn(_insert(rows), site="record_delivery_write")
|
||||
|
||||
|
||||
def _kind(note_type: str | None, status: str | None, task_kind: str | None) -> str:
|
||||
# A task is told by its status; its kind says what sort of task it is.
|
||||
if status is not None:
|
||||
return f"task:{task_kind or 'work'}"
|
||||
return note_type or "note"
|
||||
|
||||
|
||||
async def _kinds(session, user_id: int, ids) -> dict[int, str]:
|
||||
"""`{note_id: kind}` for the ids this user may read; any other id is left
|
||||
out, so the ledger never records a record its reader could not open."""
|
||||
rows = (await session.execute(
|
||||
select(Note.id, Note.note_type, Note.status, Note.task_kind)
|
||||
.where(Note.id.in_(list(ids)), readable_notes_clause(user_id))
|
||||
)).all()
|
||||
return {int(i): _kind(t, s, k) for i, t, s, k in rows}
|
||||
|
||||
|
||||
async def _insert(rows: list[dict]) -> None:
|
||||
"""Write rows, each with its record's kind. An id that is not a record (a
|
||||
rule id in a mixed list, a deleted note) is dropped. A record the session
|
||||
already opened within the open window is stamped opened as it is
|
||||
written, as `rule_deliveries` does: it reached a reader who has it."""
|
||||
now = datetime.now(timezone.utc)
|
||||
async with async_session() as session:
|
||||
kinds: dict[tuple[int, int], str] = {}
|
||||
for uid in {r["user_id"] for r in rows}:
|
||||
found = await _kinds(session, uid, {r["note_id"] for r in rows if r["user_id"] == uid})
|
||||
kinds.update({(uid, nid): k for nid, k in found.items()})
|
||||
rows = [{**r, "kind": kinds[(r["user_id"], r["note_id"])]}
|
||||
for r in rows if (r["user_id"], r["note_id"]) in kinds]
|
||||
if not rows:
|
||||
return
|
||||
keys = list({(r["user_id"], r["session_id"], r["note_id"]) for r in rows})
|
||||
read = {tuple(k) for k in (await session.execute(
|
||||
select(RecordDelivery.user_id, RecordDelivery.session_id, RecordDelivery.note_id)
|
||||
.where(
|
||||
tuple_(RecordDelivery.user_id, RecordDelivery.session_id, RecordDelivery.note_id).in_(keys),
|
||||
RecordDelivery.opened_at >= now - rule_deliveries.OPEN_WINDOW,
|
||||
)
|
||||
.distinct()
|
||||
)).all()}
|
||||
for r in rows:
|
||||
if (r["user_id"], r["session_id"], r["note_id"]) in read:
|
||||
r["opened_at"] = now
|
||||
session.add_all(RecordDelivery(**r) for r in rows)
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def from_search(user_id: int, session_id: str | None, query: str, plugin: str | None = None) -> int:
|
||||
"""Record the results of a search this session ran itself, as `asked`.
|
||||
|
||||
The MCP call does not know its session; the plugin does, and reports the
|
||||
query after the call. The server's own log of that call
|
||||
(`retrieval_logs`, source `mcp_search`) holds what it returned, so the
|
||||
report is matched to the latest logged call with the same query in
|
||||
`SEARCH_MATCH_WINDOW`. Returns how many records were recorded.
|
||||
"""
|
||||
sid = rule_deliveries.clean_session(session_id)
|
||||
if not sid or not (query or "").strip():
|
||||
return 0
|
||||
since = datetime.now(timezone.utc) - SEARCH_MATCH_WINDOW
|
||||
async with async_session() as session:
|
||||
result_ids = (await session.execute(
|
||||
select(RetrievalLog.result_ids)
|
||||
.where(RetrievalLog.user_id == user_id, RetrievalLog.source == SEARCH_SOURCE,
|
||||
RetrievalLog.query == query, RetrievalLog.created_at >= since)
|
||||
.order_by(RetrievalLog.created_at.desc(), RetrievalLog.id.desc())
|
||||
.limit(1)
|
||||
)).scalar_one_or_none()
|
||||
ids = [int(h["id"]) for h in (result_ids or []) if isinstance(h, dict) and str(h.get("id", "")).isdigit()]
|
||||
if not ids:
|
||||
return 0
|
||||
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": n, "way": ASKED,
|
||||
"source": SEARCH_SOURCE, "plugin": plugin} for n in dict.fromkeys(ids)]
|
||||
await _insert(rows)
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def mark_opened(user_id: int, session_id: str | None, note_id: int, plugin: str | None = None) -> str:
|
||||
"""Stamp this session's latest unopened delivery of the record, within the
|
||||
open window. With none, write a `direct` row: the session reached the
|
||||
record without being shown it. Returns the way the open is counted
|
||||
under, or "" when nothing was recorded."""
|
||||
sid = rule_deliveries.clean_session(session_id)
|
||||
if not sid or not note_id:
|
||||
return ""
|
||||
now = datetime.now(timezone.utc)
|
||||
async with async_session() as session:
|
||||
latest = (await session.execute(
|
||||
select(RecordDelivery.id, RecordDelivery.way)
|
||||
.where(
|
||||
RecordDelivery.user_id == user_id,
|
||||
RecordDelivery.session_id == sid,
|
||||
RecordDelivery.note_id == int(note_id),
|
||||
RecordDelivery.opened_at.is_(None),
|
||||
RecordDelivery.delivered_at >= now - rule_deliveries.OPEN_WINDOW,
|
||||
)
|
||||
.order_by(RecordDelivery.delivered_at.desc(), RecordDelivery.id.desc())
|
||||
.limit(1)
|
||||
)).first()
|
||||
if latest is not None:
|
||||
await session.execute(
|
||||
update(RecordDelivery).where(RecordDelivery.id == latest[0]).values(opened_at=now)
|
||||
)
|
||||
await session.commit()
|
||||
return str(latest[1])
|
||||
kinds = await _kinds(session, int(user_id), {int(note_id)})
|
||||
if int(note_id) not in kinds:
|
||||
return ""
|
||||
already = (await session.execute(
|
||||
select(RecordDelivery.id).where(
|
||||
RecordDelivery.user_id == user_id, RecordDelivery.session_id == sid,
|
||||
RecordDelivery.note_id == int(note_id),
|
||||
RecordDelivery.opened_at >= now - rule_deliveries.OPEN_WINDOW,
|
||||
).limit(1)
|
||||
)).scalar_one_or_none()
|
||||
if already is not None:
|
||||
# Read again: the first open was counted where it happened.
|
||||
return ""
|
||||
session.add(RecordDelivery(
|
||||
user_id=int(user_id), session_id=sid, note_id=int(note_id), kind=kinds[int(note_id)],
|
||||
way=DIRECT, source=DIRECT_SOURCE, delivered_at=now, opened_at=now, plugin=plugin,
|
||||
))
|
||||
await session.commit()
|
||||
return DIRECT
|
||||
|
||||
|
||||
async def summary(user_id: int, days: int = 30) -> dict:
|
||||
"""How records reached this user's sessions over the last `days`.
|
||||
|
||||
Per kind: `delivered` and `opened` rows for each way a record arrived
|
||||
(`pushed` by a hook, `asked` through the session's own search, `direct`
|
||||
when it was opened with nothing delivering it), and per door. A `direct`
|
||||
row is always opened; it is counted so the readout shows how much a
|
||||
session reaches without being shown.
|
||||
"""
|
||||
days = max(1, min(int(days or 30), rule_deliveries.RETAIN_DAYS))
|
||||
since = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(
|
||||
RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source,
|
||||
func.count(RecordDelivery.id),
|
||||
func.sum(case((RecordDelivery.opened_at.is_not(None), 1), else_=0)),
|
||||
func.count(func.distinct(RecordDelivery.session_id)),
|
||||
)
|
||||
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
|
||||
RecordDelivery.plugin.is_not(None))
|
||||
.group_by(RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source)
|
||||
)).all()
|
||||
sessions = (await session.execute(
|
||||
select(func.count(func.distinct(RecordDelivery.session_id)))
|
||||
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
|
||||
RecordDelivery.plugin.is_not(None))
|
||||
)).scalar_one()
|
||||
|
||||
def zero() -> dict:
|
||||
return {w: {"delivered": 0, "opened": 0} for w in (PUSHED, ASKED, DIRECT)}
|
||||
|
||||
kinds: dict[str, dict] = {}
|
||||
totals = zero()
|
||||
for kind, way, source, delivered, opened, _sessions in rows:
|
||||
slot = kinds.setdefault(kind, {"kind": kind, "ways": zero(), "sources": []})
|
||||
for bucket in (slot["ways"], totals):
|
||||
bucket[way]["delivered"] += int(delivered)
|
||||
bucket[way]["opened"] += int(opened or 0)
|
||||
slot["sources"].append({"way": way, "source": source,
|
||||
"delivered": int(delivered), "opened": int(opened or 0)})
|
||||
for slot in kinds.values():
|
||||
slot["sources"].sort(key=lambda s: (-s["delivered"], s["source"]))
|
||||
by_kind = sorted(kinds.values(),
|
||||
key=lambda k: (-sum(w["delivered"] for w in k["ways"].values()), k["kind"]))
|
||||
return {"days": days, "sessions": int(sessions or 0), "totals": totals, "by_kind": by_kind}
|
||||
|
||||
|
||||
async def prune(cutoff: datetime) -> int:
|
||||
async with async_session() as session:
|
||||
result = await session.execute(delete(RecordDelivery).where(RecordDelivery.delivered_at < cutoff))
|
||||
await session.commit()
|
||||
return int(result.rowcount or 0)
|
||||
@@ -1718,6 +1718,17 @@ async def retrieval_summary(
|
||||
out["rule_usage"] = rule_usage
|
||||
out["system_usage"] = await _system_usage(user_id, since)
|
||||
out["moment_usage"] = await moment_usage(user_id, since)
|
||||
# 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
|
||||
# how many were opened each way. Its own guard, so a failure flags itself.
|
||||
try:
|
||||
from grimoire.services import record_deliveries
|
||||
out["record_reach"] = (await record_deliveries.summary(user_id, days=days)
|
||||
if user_id else None)
|
||||
except Exception:
|
||||
logger.exception("record reach read failed")
|
||||
out["record_reach"] = None
|
||||
out["record_reach_failed"] = True
|
||||
|
||||
# ── Judged lines ─────────────────────────────────────────────────────
|
||||
#
|
||||
|
||||
@@ -64,6 +64,9 @@ 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:
|
||||
@@ -91,6 +94,11 @@ def current_session() -> str:
|
||||
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.
|
||||
@@ -252,8 +260,9 @@ async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
|
||||
|
||||
|
||||
async def prune(retain_days: int = RETAIN_DAYS) -> int:
|
||||
"""Delete deliveries older than `retain_days`, and the adherence verdicts
|
||||
on them (`rule_adherence`), which mean nothing without their delivery."""
|
||||
"""Delete deliveries older than `retain_days`, the adherence verdicts on
|
||||
them (`rule_adherence`), which mean nothing without their delivery, and
|
||||
the record deliveries of the same age (`record_deliveries`)."""
|
||||
from grimoire.services import rule_adherence
|
||||
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
|
||||
@@ -263,6 +272,8 @@ async def prune(retain_days: int = RETAIN_DAYS) -> int:
|
||||
)
|
||||
await session.commit()
|
||||
await rule_adherence.prune(cutoff)
|
||||
from grimoire.services import record_deliveries
|
||||
await record_deliveries.prune(cutoff)
|
||||
return int(result.rowcount or 0)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user