"""Real-Postgres tests for the cue-swap gate: its comparison set is the user's own recent cues on one surface and scope, read from `retrieval_logs`.""" import pytest from sqlalchemy import delete from grimoire.models import async_session from grimoire.models.retrieval_log import RetrievalLog from grimoire.services import cue_gate from tests.helpers import ensure_user pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")] SOURCE = "auto_inject" async def _user() -> int: async with async_session() as s: user = await ensure_user(s, "cue_gate_owner") uid = user.id await s.commit() await s.execute(delete(RetrievalLog).where(RetrievalLog.user_id == uid)) await s.commit() cue_gate.forget(uid) return uid async def _cues(uid, scores, *, project_id=None, source=SOURCE): async with async_session() as s: for score in scores: s.add(RetrievalLog(user_id=uid, source=source, query="q", project_id=project_id, result_count=0, result_ids=[], best_available_score=score)) await s.commit() async def test_the_bar_is_read_from_this_users_cues_on_this_surface_and_project(): uid = await _user() await _cues(uid, [i / 100 for i in range(100)], project_id=5) # Another surface's cues and another project's do not move it. await _cues(uid, [0.99] * 50, project_id=5, source="write_path") await _cues(uid, [0.99] * 50, project_id=6) gate = await cue_gate.gate_for(uid, SOURCE, 5) assert gate.scope == "project" and gate.sample == 100 assert gate.bar == pytest.approx(0.90) assert gate.passes(0.91) and not gate.passes(0.89) async def test_a_project_with_too_few_cues_borrows_the_users_cues_everywhere(): uid = await _user() await _cues(uid, [0.5] * 30, project_id=7) await _cues(uid, [0.6] * 5, project_id=8) gate = await cue_gate.gate_for(uid, SOURCE, 8) assert gate.scope == "all" and gate.sample == 35 async def test_with_too_few_cues_anywhere_nothing_passes(): uid = await _user() await _cues(uid, [0.5] * 5) gate = await cue_gate.gate_for(uid, SOURCE, None) assert gate.bar is None and not gate.passes(0.99) async def test_the_readout_counts_how_often_a_surface_spoke(): uid = await _user() await _cues(uid, [0.5] * 25) async with async_session() as s: for kept in (0, 0, 2, 1): s.add(RetrievalLog(user_id=uid, source=SOURCE, query="q", result_count=0, result_ids=[], gate_bar=0.8, gate_kept=kept)) await s.commit() (row,) = await cue_gate.readout(uid, [(SOURCE, "records")]) assert row["calls"] == 4 and row["fired"] == 2 and row["sample"] == 25