fix(memory): sanitize raw history before lossless chunking

This commit is contained in:
Xubin Ren committed 2026-09-17 21:13:23 +08:00
1 parent d4e23dec12
commit 122a0f5d6f
2 files changed
+86 -11

No files matched your search

+15 -10
View File
@@ -300,19 +300,21 @@ class MemoryStore:
content more tightly; this default only exists to catch unintentional
large writes (e.g. an LLM echoing its input back as a "summary").
"""
ts = datetime.now().strftime("%Y-%m-%d %H:%M")
raw = entry.rstrip()
content = self._normalize_history_entry(entry, max_chars=max_chars)
if entry.rstrip() and not content:
logger.debug(
"history entry stripped to empty (likely template leak); "
"persisting empty content to avoid re-polluting Dream input",
)
return self._append_history_record(content, session_key=session_key)
def _append_history_record(self, content: str, *, session_key: str | None = None) -> int:
"""Persist already sanitized, bounded content without rewriting chunk edges."""
ts = datetime.now().strftime("%Y-%m-%d %H:%M")
# Cursor allocation and the append must be atomic: concurrent writers
# could otherwise read the same current cursor and emit duplicates.
with self._append_lock:
cursor = self._next_cursor()
if raw and not content:
logger.debug(
"history entry {} stripped to empty (likely template leak); "
"persisting empty content to avoid re-polluting Dream input",
cursor,
)
record = {"cursor": cursor, "timestamp": ts, "content": content}
if session_key:
record["session_key"] = session_key
@@ -672,14 +674,17 @@ class MemoryStore:
"""Persist raw messages in bounded chunks and return a checkpoint."""
limit = max_chars if max_chars is not None else _RAW_ARCHIVE_MAX_CHARS
chunk_size = min(max(1, limit), _HISTORY_ENTRY_HARD_CAP - 1_000)
formatted = self._format_messages(public_history_messages(messages))
# Clean the complete text first: a thinking block may span chunk boundaries.
formatted = strip_think(self._format_messages(public_history_messages(messages)))
chunks = [
formatted[start:start + chunk_size]
for start in range(0, len(formatted), chunk_size)
] or [""]
for part, chunk in enumerate(chunks, start=1):
suffix = f" (part {part}/{len(chunks)})" if len(chunks) > 1 else ""
self.append_history(
# The whole text is sanitized and each record fits the hard cap.
# Normalizing again would trim meaningful whitespace at chunk edges.
self._append_history_record(
f"[RAW] {len(messages)} messages{suffix}\n{chunk}",
session_key=session_key,
)