dp-zp-agent/tools/answers/context_store.py
jp170na db671f15ba mená a pamäť
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 06:07:04 +01:00

150 lines
6.5 KiB
Python

"""Conversation steps of /rag and /graphrag, kept on the server under a short token.
Every combined answer is one step: what the next message may continue (the
question as answered, the shown people and works, the offered choices, the id
of the not yet shown items, the wiki's and CRZP's own context tokens, which
source answered). Claude gets only "zc3.<step id>.<signature>" (about 40
characters, so it cannot be cut or mistyped like the long signed tokens) and
sends it back with the next message.
A step points to the step it continued (parent), so a conversation is a chain
that can be read back (find the older step a message refers to). Steps are
never changed: a message edited in Claude continues an older step and starts
its own branch.
Storage stays small and private: a local SQLite file in data/ (gitignored, the
same file as the paged lists, WAL mode for parallel answers); no answer texts,
only the context above. A conversation not used for ANSWER_CONTEXT_DAYS (7)
is deleted, every use extends it; above ANSWER_CONTEXT_MAX_MB (50) the least
recently used conversations are deleted. ANSWER_CONTEXT_STORE=0 turns the
store off (the long signed zc2 token is used again).
"""
from __future__ import annotations
import json
import os
import secrets
import sqlite3
import threading
import time
from contextlib import contextmanager
from pathlib import Path
MAX_CHAIN = 30 # steps read back from one step (a safety cap, not a conversation limit)
_lock = threading.Lock()
def enabled() -> bool:
return os.getenv("ANSWER_CONTEXT_STORE", "1") != "0"
def _days() -> float:
try:
return max(0.01, float(os.getenv("ANSWER_CONTEXT_DAYS", "7")))
except ValueError:
return 7.0
def _max_bytes() -> int:
try:
return int(max(1.0, float(os.getenv("ANSWER_CONTEXT_MAX_MB", "50"))) * 1024 * 1024)
except ValueError:
return 50 * 1024 * 1024
def store_file() -> Path:
"""data/conversation_pages.sqlite (ANSWER_CONTEXT_FILE elsewhere, e.g. for tests); also the paged lists."""
if os.getenv("ANSWER_CONTEXT_FILE"):
return Path(os.environ["ANSWER_CONTEXT_FILE"])
from tools.rag.common import DB_FILE
return DB_FILE.parent / "conversation_pages.sqlite"
@contextmanager
def _db():
"""One short transaction (WAL: answers read while another one writes); the connection is closed."""
connection = sqlite3.connect(store_file(), timeout=10)
try:
connection.execute("PRAGMA journal_mode=WAL")
connection.execute("CREATE TABLE IF NOT EXISTS conversations (conv TEXT PRIMARY KEY, last_used REAL NOT NULL)")
connection.execute("CREATE TABLE IF NOT EXISTS steps (id TEXT PRIMARY KEY, conv TEXT NOT NULL, parent TEXT, "
"created REAL NOT NULL, payload TEXT NOT NULL)")
connection.execute("CREATE INDEX IF NOT EXISTS steps_conv ON steps (conv)")
connection.execute("CREATE INDEX IF NOT EXISTS conversations_used ON conversations (last_used)")
with connection:
yield connection
finally:
connection.close()
def _used_bytes(connection: sqlite3.Connection) -> int:
pages = connection.execute("PRAGMA page_count").fetchone()[0]
free = connection.execute("PRAGMA freelist_count").fetchone()[0]
return (pages - free) * connection.execute("PRAGMA page_size").fetchone()[0]
def _clean(connection: sqlite3.Connection, now: float) -> None:
"""Delete expired conversations; above the size cap the least recently used ones."""
old = now - _days() * 86400
connection.execute("DELETE FROM steps WHERE conv IN (SELECT conv FROM conversations WHERE last_used < ?)", (old,))
connection.execute("DELETE FROM conversations WHERE last_used < ?", (old,))
for _ in range(5):
if _used_bytes(connection) <= _max_bytes():
break
count = connection.execute("SELECT COUNT(*) FROM conversations").fetchone()[0]
if count <= 1:
break
oldest = "SELECT conv FROM conversations ORDER BY last_used LIMIT ?"
limit = max(1, count // 10)
connection.execute(f"DELETE FROM steps WHERE conv IN ({oldest})", (limit,))
connection.execute(f"DELETE FROM conversations WHERE conv IN ({oldest})", (limit,))
def save(payload: dict, parent: str | None = None) -> str | None:
"""Store one step after `parent` (the step the message continued); its id, or None."""
step = secrets.token_urlsafe(12) # 16 characters, 96 random bits
now = time.time()
try:
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
with _lock, _db() as connection:
row = connection.execute("SELECT conv FROM steps WHERE id = ?", (parent,)).fetchone() if parent else None
conv = row[0] if row else secrets.token_urlsafe(12)
connection.execute("INSERT INTO steps VALUES (?, ?, ?, ?, ?)", (step, conv, parent if row else None, now, body))
connection.execute("INSERT INTO conversations VALUES (?, ?) ON CONFLICT(conv) DO UPDATE SET last_used = ?",
(conv, now, now))
_clean(connection, now)
return step
except (sqlite3.Error, OSError, TypeError, ValueError):
return None
def chain(step: str | None, limit: int = MAX_CHAIN) -> list[dict]:
"""The step and the steps before it, newest first ({"id", "payload"}); [] for an unknown or
expired step. Reading a conversation extends its lifetime."""
if not isinstance(step, str) or not step:
return []
now = time.time()
try:
with _lock, _db() as connection:
first = connection.execute("SELECT s.conv FROM steps s JOIN conversations c ON c.conv = s.conv "
"WHERE s.id = ? AND c.last_used >= ?", (step, now - _days() * 86400)).fetchone()
if not first:
return []
connection.execute("UPDATE conversations SET last_used = ? WHERE conv = ?", (now, first[0]))
steps, current = [], step
while current and len(steps) < limit:
row = connection.execute("SELECT parent, payload FROM steps WHERE id = ?", (current,)).fetchone()
if not row:
break
steps.append({"id": current, "payload": json.loads(row[1])})
current = row[0]
return steps
except (sqlite3.Error, OSError, ValueError):
return []
def load(step: str | None) -> dict | None:
"""One step's payload (extends the conversation's lifetime), or None."""
steps = chain(step, limit=1)
return steps[0]["payload"] if steps else None