"""Real-Postgres tests for `record_deliveries`: every non-rule record put in front of a session, the way it arrived (pushed, asked, direct), and the open stamped on the delivery it followed.""" from datetime import datetime, timedelta, timezone import pytest from sqlalchemy import delete, select from grimoire.models import async_session from grimoire.models.note import Note from grimoire.models.record_delivery import RecordDelivery from grimoire.models.retrieval_log import RetrievalLog from grimoire.services import background, note_usage, record_deliveries, rule_deliveries from tests.helpers import ensure_user pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")] PLUGIN = "2026.11.24.1900" async def _setup(name: str = "record_delivery_owner") -> tuple[int, dict[str, int]]: """A user with one record of each kind the readout tells apart.""" async with async_session() as s: user = await ensure_user(s, name) uid = user.id await s.execute(delete(RecordDelivery).where(RecordDelivery.user_id == uid)) await s.execute(delete(RetrievalLog).where(RetrievalLog.user_id == uid)) notes = { "snippet": Note(user_id=uid, title="a snippet", note_type="snippet"), "note": Note(user_id=uid, title="a note", note_type="note"), "issue": Note(user_id=uid, title="an issue", status="todo", task_kind="issue"), "lesson": Note(user_id=uid, title="a lesson", note_type="lesson"), } s.add_all(notes.values()) await s.commit() return uid, {k: n.id for k, n in notes.items()} async def _rows(uid: int) -> list[RecordDelivery]: async with async_session() as s: return list((await s.execute( select(RecordDelivery).where(RecordDelivery.user_id == uid).order_by(RecordDelivery.id) )).scalars().all()) async def _push(uid, sid, ids, source="write_path_semantic", kept=None): """What a plugin door does: bind the session, surface, fit, flush.""" rule_deliveries.bind_session(sid, PLUGIN) try: note_usage.record_surfaced(user_id=uid, note_ids=ids, source=source) record_deliveries.flush(kept) await background.drain() finally: rule_deliveries.bind_session("") async def test_a_pushed_line_is_recorded_with_its_kind_only_when_the_payload_kept_it(): uid, n = await _setup() await _push(uid, "s-1", [n["snippet"], n["issue"], n["lesson"]], kept={n["snippet"], n["issue"]}) rows = await _rows(uid) assert [(r.note_id, r.kind, r.way, r.source, r.plugin) for r in rows] == [ (n["snippet"], "snippet", "pushed", "write_path_semantic", PLUGIN), (n["issue"], "task:issue", "pushed", "write_path_semantic", PLUGIN), ] async def test_nothing_is_recorded_outside_a_session_or_for_a_synced_skill(): uid, n = await _setup() note_usage.record_surfaced(user_id=uid, note_ids=[n["note"]], source="auto_inject") await _push(uid, "s-1", [n["note"]], source="process_skill_sync") await background.drain() assert await _rows(uid) == [] async def test_a_record_the_reader_cannot_read_is_not_recorded(): uid, _n = await _setup() _other, theirs = await _setup("record_delivery_stranger") await _push(uid, "s-1", [theirs["note"]]) assert await _rows(uid) == [] assert await record_deliveries.mark_opened(uid, "s-1", theirs["note"]) == "" async def test_an_open_is_stamped_on_the_delivery_it_followed_and_otherwise_counts_as_direct(): uid, n = await _setup() await _push(uid, "s-1", [n["snippet"]]) assert await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN) == "pushed" # Nothing delivered the note to this session: reached on its own. assert await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN) == "direct" # Opened again: the first open was already counted. assert await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN) == "" rows = {(r.note_id, r.way): r.opened_at is not None for r in await _rows(uid)} assert rows == {(n["snippet"], "pushed"): True, (n["note"], "direct"): True} async def test_a_search_the_session_ran_records_its_results_as_asked(): uid, n = await _setup() async with async_session() as s: s.add(RetrievalLog(user_id=uid, source="mcp_search", query="how is the lock released", result_count=2, result_ids=[{"id": n["issue"], "score": 0.8, "rank": 1}, {"id": n["note"], "score": 0.7, "rank": 2}])) s.add(RetrievalLog(user_id=uid, source="mcp_search", query="something else", result_count=1, result_ids=[{"id": n["lesson"], "score": 0.9, "rank": 1}])) await s.commit() assert await record_deliveries.from_search(uid, "s-1", "how is the lock released", PLUGIN) == 2 assert await record_deliveries.from_search(uid, "s-1", "never searched", PLUGIN) == 0 assert await record_deliveries.mark_opened(uid, "s-1", n["issue"], PLUGIN) == "asked" assert sorted((r.note_id, r.way) for r in await _rows(uid)) == sorted( [(n["issue"], "asked"), (n["note"], "asked")]) async def test_a_record_already_opened_in_the_session_counts_as_opened_when_pushed_again(): uid, n = await _setup() assert await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN) == "direct" await _push(uid, "s-1", [n["snippet"]]) await _push(uid, "s-2", [n["snippet"]]) later = {r.session_id: r.opened_at is not None for r in await _rows(uid) if r.way == "pushed"} assert later == {"s-1": True, "s-2": False} async def test_the_readout_counts_each_way_per_kind_from_plugins_that_report_opens(): uid, n = await _setup() await _push(uid, "s-1", [n["snippet"], n["issue"]]) await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN) await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN) # A row from a plugin that never reports opens says nothing about them. async with async_session() as s: s.add(RecordDelivery(user_id=uid, session_id="old", note_id=n["lesson"], kind="lesson", way="pushed", source="write_path_semantic", plugin=None, delivered_at=datetime.now(timezone.utc) - timedelta(minutes=1))) await s.commit() out = await record_deliveries.summary(uid, days=7) kinds = {k["kind"]: k["ways"] for k in out["by_kind"]} assert kinds["snippet"]["pushed"] == {"delivered": 1, "opened": 1} assert kinds["task:issue"]["pushed"] == {"delivered": 1, "opened": 0} assert kinds["note"]["direct"] == {"delivered": 1, "opened": 1} assert "lesson" not in kinds assert out["totals"]["pushed"] == {"delivered": 2, "opened": 1} assert out["sessions"] == 1