Coverage for app / memory / recall.py: 99%
106 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""Which of a person's memories reach the model for one request.
3Recall used to be the newest eight memories from the person's other
4conversations, whatever the request — so a question about banana bread was
5answered beside summaries of the last eight things discussed, and anything
6older than those eight was never recalled at all. Irrelevant context is not
7free: models are measurably distracted by it (Shi et al. 2023; Cuconasu et
8al. 2024), and every token of it is paid for on every answering call.
10Now:
12* **Preferences always come.** They shape how any answer is written and
13 rarely share words with the request (``kinds.POLICIES``).
14* **Everything else must be about the request**: a memory passes on either
15 leg — its words cover enough of the request's informative weight
16 (``lexical.coverage`` ≥ ``LEXICAL_FLOOR``), or its embedding is close
17 enough to the request's (≥ the embedder's floor) — and must score within
18 ``RELATIVE_FLOOR`` of the best match, so one strong match is not padded
19 with weak ones.
20* **Recency scales a match, never replaces one** (Park et al. 2023 weigh
21 recency, importance and relevance; here relevance gates and recency only
22 orders): an old memory the request is plainly about still comes back.
23* **What must not come back, does not**: a superseded memory, an expired
24 one, and an episode the replayed history already holds (the store leaves
25 those out before ranking).
26* **A request for current information recalls no episode** (``Query.live``).
27 "whats in the news" is, by meaning, closest to the last time it was asked,
28 and that turn's answer — the day's headlines, or "the search found
29 nothing" — was recalled beside the question and repeated in place of a
30 search (25 October 2026). What the person told the agent still comes;
31 what the agent answered then does not.
33When nothing passes, nothing is recalled — and the request carries no
34memory block at all.
35"""
37from __future__ import annotations
39import math
40from dataclasses import dataclass
41from datetime import datetime
43from app.memory import lexical
44from app.memory.kinds import POLICIES, MemoryKind
46#: The least share of a request's informative weight a memory's words must
47#: hold to count as about it — or, when they share at least
48#: ``LEXICAL_PAIR_TERMS`` distinct informative words, ``LEXICAL_PAIR_FLOOR``:
49#: two words in common is stronger evidence than one heavily weighted word.
50LEXICAL_FLOOR = 0.4
51LEXICAL_PAIR_FLOOR = 0.3
52LEXICAL_PAIR_TERMS = 2
53#: The fewest distinct informative words a form of the request must have for
54#: its words to vouch for a memory. "whats in the news" is one word, "news",
55#: so every memory holding it covered the whole request — the earlier "can my
56#: agent read the news?" turn, answered with granting the News repository,
57#: came back for a news question. One shared word is not evidence a memory is
58#: about the request; such a form leaves it to the dense leg (and triage's
59#: standalone form of a real follow-up usually has more words).
60LEXICAL_MIN_FORM_TERMS = 2
61#: A match below this share of the best match's score is dropped.
62RELATIVE_FLOOR = 0.35
63#: How much more an episode of the conversation under way counts: a
64#: follow-up beyond the replayed history is most likely about it.
65SAME_CONVERSATION_BOOST = 1.15
66#: Preferences recalled whatever the request (the newest, or the most
67#: relevant when there are more).
68PREFERENCE_LIMIT = 6
69#: The least a matched memory keeps of its score however old it is.
70RECENCY_FLOOR = 0.6
73@dataclass(frozen=True)
74class Candidate:
75 """One stored memory, as recall sees it."""
77 id: str
78 kind: MemoryKind
79 text: str
80 created_at: datetime
81 conversation_id: str | None = None
82 #: Its embedding, when it has one in the active embedder's space.
83 embedding: list[float] | None = None
84 #: When the person last restated it (a duplicate reconfirms it).
85 confirmed_at: datetime | None = None
87 @property
88 def last_said(self) -> datetime:
89 return max(self.created_at, self.confirmed_at or self.created_at)
92@dataclass(frozen=True)
93class Recalled:
94 """A memory recall chose, with why."""
96 candidate: Candidate
97 score: float
98 #: ``always`` (a preference) or ``relevant``.
99 reason: str
100 lexical: float = 0.0
101 dense: float | None = None
104@dataclass(frozen=True)
105class Query:
106 """What recall matches memories against."""
108 #: The request, and its standalone form (the gate's rewrite of a
109 #: follow-up), when there is one. Both are matched; the better counts.
110 texts: tuple[str, ...]
111 embedding: list[float] | None = None
112 conversation_id: str | None = None
113 #: The cosine similarity an embedding match must reach — the
114 #: embedder's own (each model's scores sit in their own range).
115 dense_floor: float = 1.0
116 #: The request asks for current information (triage sent it to the web,
117 #: or named a web tool for it): no earlier exchange is recalled, since
118 #: none is current and the closest is the same question answered then.
119 live: bool = False
122@dataclass(frozen=True)
123class Limits:
124 """How much one request may recall — its cost profile's."""
126 #: Memories recalled for relevance (preferences come on top).
127 limit: int = 8
128 #: The most characters the whole block may take.
129 max_chars: int = 6_000
130 #: Longest single memory sent.
131 item_max_chars: int = 1_500
132 preference_limit: int = PREFERENCE_LIMIT
135def _cosine(a: list[float], b: list[float]) -> float | None:
136 if not a or not b or len(a) != len(b):
137 return None
138 dot = sum(x * y for x, y in zip(a, b))
139 na = math.sqrt(sum(x * x for x in a))
140 nb = math.sqrt(sum(y * y for y in b))
141 if na == 0 or nb == 0:
142 return None
143 return dot / (na * nb)
146def _recency(candidate: Candidate, now: datetime) -> float:
147 half_life = POLICIES[candidate.kind].half_life_days
148 if half_life is None:
149 return 1.0
150 age_days = max(0.0, (now - candidate.last_said).total_seconds() / 86_400)
151 return RECENCY_FLOOR + (1 - RECENCY_FLOOR) * 0.5 ** (age_days / half_life)
154def _scaled(similarity: float | None, floor: float) -> float:
155 """A cosine above the floor as 0–1; at or below it, 0."""
156 if similarity is None or similarity <= floor or floor >= 1:
157 return 0.0
158 return min(1.0, (similarity - floor) / (1 - floor))
161def rank(
162 query: Query,
163 candidates: list[Candidate],
164 *,
165 now: datetime,
166 limits: Limits | None = None,
167) -> list[Recalled]:
168 """The memories to recall for ``query``, best first, within ``limits``."""
169 limits = limits or Limits()
170 if not candidates:
171 return []
172 documents = [lexical.document_terms(c.text) for c in candidates]
173 corpus = lexical.Corpus(documents)
174 forms = [lexical.terms(t) for t in query.texts if t and t.strip()]
176 preferences: list[Recalled] = []
177 matched: list[Recalled] = []
178 for candidate, words in zip(candidates, documents):
179 if query.live and candidate.kind is MemoryKind.episode:
180 continue
181 lex, shared = max(
182 (
183 (lexical.coverage(f, words, corpus), len(set(f) & set(words)))
184 for f in forms
185 if len(set(f)) >= LEXICAL_MIN_FORM_TERMS
186 ),
187 default=(0.0, 0),
188 )
189 dense = (
190 _cosine(query.embedding, candidate.embedding)
191 if query.embedding is not None and candidate.embedding is not None
192 else None
193 )
194 dense_part = _scaled(dense, query.dense_floor)
195 lex_part = (
196 lex
197 if lex >= LEXICAL_FLOOR
198 or (shared >= LEXICAL_PAIR_TERMS and lex >= LEXICAL_PAIR_FLOOR)
199 else 0.0
200 )
201 relevance = max(lex_part, dense_part) + 0.25 * min(lex_part, dense_part)
202 policy = POLICIES[candidate.kind]
203 boost = (
204 SAME_CONVERSATION_BOOST
205 if query.conversation_id
206 and candidate.conversation_id == query.conversation_id
207 else 1.0
208 )
209 score = relevance * policy.weight * _recency(candidate, now) * boost
210 if policy.always:
211 preferences.append(
212 Recalled(candidate, score, "always", lexical=lex, dense=dense)
213 )
214 elif relevance > 0:
215 matched.append(
216 Recalled(candidate, score, "relevant", lexical=lex, dense=dense)
217 )
219 preferences.sort(key=lambda r: (r.score, r.candidate.last_said), reverse=True)
220 matched.sort(key=lambda r: (r.score, r.candidate.last_said), reverse=True)
221 if matched:
222 best = matched[0].score
223 matched = [r for r in matched if r.score >= best * RELATIVE_FLOOR]
225 chosen = preferences[: limits.preference_limit] + matched[: limits.limit]
226 return _within(chosen, limits)
229def _within(chosen: list[Recalled], limits: Limits) -> list[Recalled]:
230 """``chosen`` held to the block's size, dropping from the end (the
231 weakest matches) first; preferences, first in the list, go last."""
232 kept: list[Recalled] = []
233 total = 0
234 for recalled in chosen:
235 size = min(len(recalled.candidate.text), limits.item_max_chars)
236 if total + size > limits.max_chars:
237 continue
238 kept.append(recalled)
239 total += size
240 return kept