Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 34 additions & 13 deletions server/insights/app/mentor.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,15 @@
# Caches
# ---------------------------------------------------------------------------

_cache: dict[tuple[str, str, str], tuple[float, MentorProfile | None]] = {}
_cache: dict[tuple[str, str, str, int], tuple[float, MentorProfile | None]] = {}
_sessions: dict[str, dict[str, Any]] = {}
_inflight: dict[tuple[str, str, str], asyncio.Task[Any]] = {}
# Profile hint codes already shown to an agent within the profile's TTL: a
# profile hint says something about the agent's week, so it is said once per
# agent per hour, not once per session — a bot that opens forty short
# sessions an hour would otherwise read the same sentence forty times.
# Per-call rules stay per session; the pack section stays per session.
# Keyed like `_cache` and evicted with it, so it is bounded the same way.
# Evicted with the default-window profile.
_profile_shown: dict[tuple[str, str, str], set[str]] = {}

# Callers the mentor never speaks to: the dashboard and the assistant toolset, which
Expand Down Expand Up @@ -123,28 +123,38 @@ def reset_cache() -> None:
_profile_shown.clear()


def _cache_put(key: tuple[str, str, str], expires_at: float, value: MentorProfile | None) -> None:
def _cache_put(
identity: tuple[str, str, str],
expires_at: float,
value: MentorProfile | None,
*,
window_seconds: int = WINDOW_SECONDS_DEFAULT,
) -> None:
key = (*identity, window_seconds)
if key not in _cache and len(_cache) >= CACHE_MAX_ENTRIES:
oldest = min(_cache, key=lambda k: _cache[k][0])
_cache.pop(oldest, None)
_profile_shown.pop(oldest, None)
if oldest[3] == WINDOW_SECONDS_DEFAULT:
_profile_shown.pop(oldest[:3], None)
_cache[key] = (expires_at, value)
if window_seconds != WINDOW_SECONDS_DEFAULT:
return
# A fresh profile starts a fresh "already said" set — seeded with the
# codes the ledger saw this agent shown within the TTL:
# each uvicorn worker keeps its own set, so a session spread over four
# workers would read one profile hint four times.
shown = (value.facts.get("shown_codes") if value is not None else None) or ()
if shown:
_profile_shown[key] = {str(c) for c in shown}
_profile_shown[identity] = {str(c) for c in shown}
else:
_profile_shown.pop(key, None)
_profile_shown.pop(identity, None)


def cached_profile(
org: str, namespace: str, agent: str, *, clock: Callable[[], float] = time.monotonic
) -> MentorProfile | None:
"""The profile if the cache holds a live one; no read otherwise."""
hit = _cache.get((str(org), str(namespace), str(agent)))
"""The live default-window profile if cached; no read otherwise."""
hit = _cache.get((str(org), str(namespace), str(agent), WINDOW_SECONDS_DEFAULT))
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
if hit is not None and hit[0] > clock():
return hit[1]
return None
Expand Down Expand Up @@ -361,16 +371,16 @@ async def mentor_profile(
window_seconds: int = WINDOW_SECONDS_DEFAULT,
clock: Callable[[], float] = time.monotonic,
) -> MentorProfile | None:
"""The cached profile of (org, namespace, agent); None when the TTL is 0
"""The cached profile for this agent and window; None when the TTL is 0
(the mentor is off), when the read failed, or while a failure is still
remembered. Never raises."""
ttl = _ttl()
if ttl <= 0 or not org or not namespace:
return None
agent = str(agent or "-")
key = (str(org), str(namespace), agent)
identity = (str(org), str(namespace), agent)
now = clock()
hit = _cache.get(key)
hit = _cache.get((*identity, window_seconds))
if hit is not None and hit[0] > now:
return hit[1]
try:
Expand All @@ -380,15 +390,26 @@ async def mentor_profile(
profile = None
# A profile whose repository fact failed (the code registry unread, say) is short-lived.
whole = profile is not None and not any(s.startswith(f"{REPOS_FACT}:") for s in profile.skipped)
_cache_put(key, now + (ttl if whole else min(ttl, FAILURE_TTL_SECONDS)), profile)
_cache_put(
identity,
now + (ttl if whole else min(ttl, FAILURE_TTL_SECONDS)),
profile,
window_seconds=window_seconds,
)
return profile


def warm_profile(org: str, namespace: str, agent: str) -> None:
"""Start the read in the background when nothing is cached; the next
call or pack reads the result. Never blocks the caller."""
key = (str(org), str(namespace), str(agent or "-"))
if _ttl() <= 0 or not org or not namespace or key in _cache or key in _inflight:
if (
_ttl() <= 0
or not org
or not namespace
or (*key, WINDOW_SECONDS_DEFAULT) in _cache
or key in _inflight
):
return
try:
asyncio.get_running_loop()
Expand Down
23 changes: 20 additions & 3 deletions tests/unit/test_mentor.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,24 @@ def test_planes_carry_the_mentored_flag() -> None:
# --- cache ----------------------------------------------------------------------


def test_profile_cache_keeps_windows_separate_from_the_default(
monkeypatch: pytest.MonkeyPatch,
) -> None:
ch = _wire(monkeypatch, _store(_usage(memory__set=5), 1))
default = _profile()
hour = _profile(window_seconds=3600)
month = _profile(window_seconds=30 * 86400)
assert default is not None and default.window_seconds == m.WINDOW_SECONDS_DEFAULT
assert hour is not None and hour.window_seconds == 3600
assert month is not None and month.window_seconds == 30 * 86400

reads = len(ch.sqls)
assert m.cached_profile("o", "ns", "a") is default
assert _profile(window_seconds=3600) is hour
assert _profile(window_seconds=30 * 86400) is month
assert len(ch.sqls) == reads


def test_profile_is_cached_per_agent_and_a_failure_is_remembered_briefly(
monkeypatch: pytest.MonkeyPatch,
) -> None:
Expand Down Expand Up @@ -2010,15 +2028,14 @@ def test_records_hint_states_the_prefix_share_and_skips_aggregate_when_used(


def test_the_shown_codes_leave_with_the_profile_the_cache_evicts(monkeypatch) -> None:
"""`_profile_shown` is keyed like the profile cache; an agent whose profile
is evicted takes its shown-codes set with it, so the map stays bounded."""
"""Evicting an agent's default-window profile also drops its shown codes."""
monkeypatch.setattr(m, "CACHE_MAX_ENTRIES", 2)
shown = {"shown_codes": ["x"]}
m._cache_put(("o", "ns", "a1"), 100.0, _fake_profile(agent="a1", facts=shown))
m._cache_put(("o", "ns", "a2"), 200.0, _fake_profile(agent="a2", facts=shown))
assert set(m._profile_shown) == {("o", "ns", "a1"), ("o", "ns", "a2")}
m._cache_put(("o", "ns", "a3"), 300.0, _fake_profile(agent="a3", facts=shown))
assert ("o", "ns", "a1") not in m._cache
assert m.cached_profile("o", "ns", "a1", clock=lambda: 0.0) is None
assert set(m._profile_shown) == {("o", "ns", "a2"), ("o", "ns", "a3")}


Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_mirror_mentor_advice.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def privacy(kind):
def test_mentor_never_inspects_or_warms_private_request_advice(world, kind, cached):
if cached:
profile = SimpleNamespace(facts={}, hints=(), hint=lambda code: None)
mentor._cache[("org-a", "team-a", "reader")] = (1000.0, profile)
mentor._cache_put(("org-a", "team-a", "reader"), 1000.0, profile)
original_cache = dict(mentor._cache)

def exercise():
Expand Down
Loading