fix(memory): rank the whole history and keep relevant recent records
- Search scored only the newest 5,000 matching records, so an old record behind enough newer chatter was never found. Both passes (word rarity counts and the score) now run in SQLite over every record in scope and only the best rows come back. - context() excluded the recent window from search and then cut that window for the budget, so a relevant recent record could vanish. Search now covers the recent window, matches keep their half of the budget, and a matched record is removed from the recent block so it appears once. - Matching used SQLite's ASCII-only lower() against Python's lowercasing. Stored text gets a folded column (NFKC + casefold) and query words are folded the same way, so case is ignored in every script. - Prompt label "Records related to this question" (matches may now be recent); eval re-run 3x on qwen2.5:7b, all pass. Spec, memory.md and roadmap updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,7 @@ import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
import unicodedata
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterable, List, Optional
|
||||
|
||||
@@ -24,7 +25,8 @@ CREATE TABLE IF NOT EXISTS history (
|
||||
author_name TEXT NOT NULL,
|
||||
to_id TEXT,
|
||||
message_id TEXT,
|
||||
text TEXT NOT NULL
|
||||
text TEXT NOT NULL,
|
||||
norm TEXT NOT NULL -- text folded for search (_fold)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS history_ts ON history(ts);
|
||||
CREATE INDEX IF NOT EXISTS history_author ON history(author_id);
|
||||
@@ -42,7 +44,6 @@ CREATE INDEX IF NOT EXISTS presence_user ON presence(user_id, channel_id);
|
||||
"""
|
||||
|
||||
_WORD = re.compile(r"\w{2,}", re.UNICODE)
|
||||
_SEARCH_CANDIDATES = 5000
|
||||
_BYTES_PER_TOKEN = 3
|
||||
|
||||
|
||||
@@ -77,11 +78,17 @@ class HistoryContext:
|
||||
matches: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _fold(text: str) -> str:
|
||||
"""One Unicode folding for stored text and query words alike (NFKC, then case folding),
|
||||
so matching does not depend on SQLite's ASCII-only lower()."""
|
||||
return unicodedata.normalize("NFKC", text).casefold()
|
||||
|
||||
|
||||
def _word_patterns(query: str) -> List[List[str]]:
|
||||
"""For each query word, its accepted forms, longest first (the word, then shorter prefixes)."""
|
||||
out: List[List[str]] = []
|
||||
seen = set()
|
||||
for w in _WORD.findall(query.lower()):
|
||||
for w in _WORD.findall(_fold(query)):
|
||||
if w in seen:
|
||||
continue
|
||||
seen.add(w)
|
||||
@@ -90,6 +97,13 @@ def _word_patterns(query: str) -> List[List[str]]:
|
||||
return out
|
||||
|
||||
|
||||
_COLUMNS = "h.id, h.ts, h.kind, h.channel_id, h.author_id, h.author_name, h.to_id, h.message_id, h.text"
|
||||
|
||||
|
||||
def _record(row: sqlite3.Row) -> Record:
|
||||
return Record(**{k: row[k] for k in Record.__dataclass_fields__})
|
||||
|
||||
|
||||
def _tokens(line: str) -> float:
|
||||
return len(line.encode("utf-8")) / _BYTES_PER_TOKEN
|
||||
|
||||
@@ -118,9 +132,9 @@ class HistoryStore:
|
||||
return None
|
||||
with self._lock:
|
||||
cur = self._conn.execute(
|
||||
"INSERT OR REPLACE INTO history(ts, kind, channel_id, author_id, author_name, to_id, message_id, text)"
|
||||
" VALUES (?,?,?,?,?,?,?,?)",
|
||||
(ts, kind, channel_id, author_id, author_name, to_id, message_id, text),
|
||||
"INSERT OR REPLACE INTO history(ts, kind, channel_id, author_id, author_name, to_id, message_id,"
|
||||
" text, norm) VALUES (?,?,?,?,?,?,?,?,?)",
|
||||
(ts, kind, channel_id, author_id, author_name, to_id, message_id, text, _fold(text)),
|
||||
)
|
||||
self._conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
@@ -141,8 +155,8 @@ class HistoryStore:
|
||||
self.delete_chat(channel_id, message_id)
|
||||
return
|
||||
with self._lock:
|
||||
self._conn.execute("UPDATE history SET text=? WHERE channel_id=? AND message_id=?",
|
||||
(text, channel_id, message_id))
|
||||
self._conn.execute("UPDATE history SET text=?, norm=? WHERE channel_id=? AND message_id=?",
|
||||
(text, _fold(text), channel_id, message_id))
|
||||
self._conn.commit()
|
||||
|
||||
def delete_chat(self, channel_id: str, message_id: str) -> None:
|
||||
@@ -178,8 +192,9 @@ class HistoryStore:
|
||||
def records_of(self, person: str) -> List[Record]:
|
||||
with self._lock:
|
||||
rows = self._conn.execute(
|
||||
"SELECT * FROM history WHERE author_id=? OR to_id=? ORDER BY ts, id", (person, person)).fetchall()
|
||||
return [Record(**dict(r)) for r in rows]
|
||||
f"SELECT {_COLUMNS} FROM history h WHERE author_id=? OR to_id=? ORDER BY ts, id",
|
||||
(person, person)).fetchall()
|
||||
return [_record(r) for r in rows]
|
||||
|
||||
def forget_person(self, person: str) -> None:
|
||||
with self._lock:
|
||||
@@ -221,48 +236,59 @@ class HistoryStore:
|
||||
where, params = self._scope_sql(asker, scope)
|
||||
with self._lock:
|
||||
rows = self._conn.execute(
|
||||
f"SELECT h.* FROM history h WHERE {where} AND h.ts >= ? AND h.ts <= ?"
|
||||
f"SELECT {_COLUMNS} FROM history h WHERE {where} AND h.ts >= ? AND h.ts <= ?"
|
||||
" ORDER BY h.ts DESC, h.id DESC LIMIT ?",
|
||||
(*params, now - minutes * 60, now, max_records)).fetchall()
|
||||
return [Record(**dict(r)) for r in reversed(rows)]
|
||||
return [_record(r) for r in reversed(rows)]
|
||||
|
||||
def _scored_search(self, asker: str, query: str, scope: Scope, limit: int,
|
||||
exclude: Iterable[int]) -> List[tuple[float, Record]]:
|
||||
"""Score every record in scope (no recency cut before scoring) and return the best ``limit``.
|
||||
|
||||
Two passes in SQLite: the first counts, per query word, how many records in scope match
|
||||
it (for the rarity weight); the second scores and ranks in SQL so only ``limit`` rows
|
||||
come back to Python.
|
||||
"""
|
||||
words = _word_patterns(query)
|
||||
if scope.off or not words or limit <= 0:
|
||||
return []
|
||||
where, params = self._scope_sql(asker, scope)
|
||||
patterns = sorted({p for forms in words for p in forms})
|
||||
match_sql = " OR ".join("instr(lower(h.text), ?) > 0" for _ in patterns)
|
||||
skip = sorted(set(exclude))
|
||||
skip_sql = f" AND h.id NOT IN ({','.join('?' * len(skip))})" if skip else ""
|
||||
any_sql = " OR ".join("instr(h.norm, ?) > 0" for forms in words for _ in forms)
|
||||
any_params = [f for forms in words for f in forms]
|
||||
|
||||
def word_hit(forms: List[str]) -> tuple[str, list]:
|
||||
# Fraction of the word matched: the longest accepted form found in the record.
|
||||
whens = " ".join("WHEN instr(h.norm, ?) > 0 THEN ?" for _ in forms)
|
||||
args: list = []
|
||||
for f in forms:
|
||||
args += [f, len(f) / len(forms[0])]
|
||||
return f"(CASE {whens} ELSE 0 END)", args
|
||||
|
||||
t0 = time.perf_counter()
|
||||
with self._lock:
|
||||
counts_sql = ", ".join(f"SUM({word_hit(forms)[0]} > 0)" for forms in words)
|
||||
counts_args = [a for forms in words for a in word_hit(forms)[1]]
|
||||
row = self._conn.execute(
|
||||
f"SELECT COUNT(*), {counts_sql} FROM history h WHERE {where} AND ({any_sql}){skip_sql}",
|
||||
(*counts_args, *params, *any_params, *skip)).fetchone()
|
||||
n = row[0] or 0
|
||||
if not n:
|
||||
return []
|
||||
weights = [math.log(1 + n / max(1, row[i + 1] or 0)) for i in range(len(words))]
|
||||
score_parts, score_args = [], []
|
||||
for w, forms in zip(weights, words):
|
||||
expr, args = word_hit(forms)
|
||||
score_parts.append(f"? * {expr}")
|
||||
score_args += [w, *args]
|
||||
rows = self._conn.execute(
|
||||
f"SELECT h.* FROM history h WHERE {where} AND ({match_sql}){skip_sql}"
|
||||
" ORDER BY h.ts DESC, h.id DESC LIMIT ?",
|
||||
(*params, *patterns, *skip, _SEARCH_CANDIDATES)).fetchall()
|
||||
records = [Record(**dict(r)) for r in rows]
|
||||
lowered = [r.text.lower() for r in records]
|
||||
# Per word: matched fraction for every candidate, then inverse document frequency.
|
||||
fractions = []
|
||||
for forms in words:
|
||||
col = []
|
||||
for text in lowered:
|
||||
hit = next((len(f) for f in forms if f in text), 0)
|
||||
col.append(hit / len(forms[0]))
|
||||
fractions.append(col)
|
||||
n = len(records)
|
||||
weights = [math.log(1 + n / max(1, sum(1 for x in col if x))) for col in fractions]
|
||||
scored = []
|
||||
for i, rec in enumerate(records):
|
||||
score = sum(w * col[i] for w, col in zip(weights, fractions))
|
||||
if score > 0:
|
||||
scored.append((score, rec))
|
||||
scored.sort(key=lambda sr: (sr[0], sr[1].ts, sr[1].id), reverse=True)
|
||||
debug_log(f"history search: {n} candidates, {len(scored)} scored, "
|
||||
f"{(time.perf_counter() - t0) * 1000:.0f} ms", "memory")
|
||||
return scored[:limit]
|
||||
f"SELECT {_COLUMNS}, ({' + '.join(score_parts)}) AS score FROM history h"
|
||||
f" WHERE {where} AND ({any_sql}){skip_sql}"
|
||||
" ORDER BY score DESC, h.ts DESC, h.id DESC LIMIT ?",
|
||||
(*score_args, *params, *any_params, *skip, limit)).fetchall()
|
||||
debug_log(f"history search: {n} candidates, {(time.perf_counter() - t0) * 1000:.0f} ms", "memory")
|
||||
return [(r["score"], _record(r)) for r in rows if r["score"] > 0]
|
||||
|
||||
def search(self, asker: str, query: str, scope: Scope, limit: int = 5,
|
||||
exclude: Iterable[int] = ()) -> List[Record]:
|
||||
@@ -276,19 +302,20 @@ class HistoryStore:
|
||||
def context(self, asker: str, query: str, now: float, scope: Scope, minutes: float = 30,
|
||||
max_records: int = 20, limit: int = 5, budget_tokens: float = 4000) -> HistoryContext:
|
||||
recent = self.recent(asker, now, scope, minutes=minutes, max_records=max_records)
|
||||
matches = self.search(asker, query, scope, limit=limit, exclude={r.id for r in recent})
|
||||
recent_lines = [self.format_line(r) for r in recent]
|
||||
match_lines = [self.format_line(r) for r in matches] # best first
|
||||
total = sum(_tokens(x) for x in recent_lines + match_lines)
|
||||
# Search the whole scope, recent records included: a recent record the question is
|
||||
# about must keep its place under the matches' share of the budget.
|
||||
matches = self.search(asker, query, scope, limit=limit) # best first
|
||||
# Matches get at most half the budget so a long recent window cannot crowd out the
|
||||
# one record the question is about; the recent window gets the rest.
|
||||
while match_lines and sum(_tokens(x) for x in match_lines) > budget_tokens / 2:
|
||||
total -= _tokens(match_lines.pop())
|
||||
while total > budget_tokens and recent_lines:
|
||||
total -= _tokens(recent_lines.pop(0))
|
||||
# Oldest match first reads like a timeline.
|
||||
by_line = dict(zip((self.format_line(r) for r in matches), matches))
|
||||
match_lines.sort(key=lambda line: by_line[line].ts)
|
||||
debug_log(f"history context: {len(recent_lines)} recent, {len(match_lines)} matches, "
|
||||
# records the question is about; the recent window gets the rest.
|
||||
while matches and sum(_tokens(self.format_line(r)) for r in matches) > budget_tokens / 2:
|
||||
matches.pop()
|
||||
kept = {r.id for r in matches}
|
||||
recent = [r for r in recent if r.id not in kept] # each record appears once
|
||||
total = sum(_tokens(self.format_line(r)) for r in recent + matches)
|
||||
while recent and total > budget_tokens:
|
||||
total -= _tokens(self.format_line(recent.pop(0)))
|
||||
matches.sort(key=lambda r: (r.ts, r.id)) # oldest first reads like a timeline
|
||||
debug_log(f"history context: {len(recent)} recent, {len(matches)} matches, "
|
||||
f"~{total:.0f} tokens", "memory")
|
||||
return HistoryContext(recent=recent_lines, matches=match_lines)
|
||||
return HistoryContext(recent=[self.format_line(r) for r in recent],
|
||||
matches=[self.format_line(r) for r in matches])
|
||||
|
||||
Reference in New Issue
Block a user