fix: make global memory durable and atomic across restarts
This commit is contained in:
1 parent
056fc2c90a
commit
ca647d2298
1 file changed
+57
-30
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
import uuid
|
import uuid
|
||||||
from dataclasses import asdict, dataclass, field
|
from dataclasses import asdict, dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -20,10 +22,14 @@ class MemoryItem:
|
|||||||
|
|
||||||
|
|
||||||
class GlobalMemory:
|
class GlobalMemory:
|
||||||
"""Persistent global memory store shared across all forum topics."""
|
"""Persistent global memory store shared across all forum topics.
|
||||||
|
|
||||||
|
Writes are atomic: a complete file is fsynced and then renamed into place,
|
||||||
|
so a container restart cannot leave a truncated JSON file behind.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self, storage_path: Path):
|
def __init__(self, storage_path: Path):
|
||||||
self.storage_path = storage_path
|
self.storage_path = Path(storage_path).expanduser().resolve()
|
||||||
self._items: dict[str, MemoryItem] = {}
|
self._items: dict[str, MemoryItem] = {}
|
||||||
self._load()
|
self._load()
|
||||||
|
|
||||||
@@ -31,8 +37,10 @@ class GlobalMemory:
|
|||||||
if not self.storage_path.exists():
|
if not self.storage_path.exists():
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
with open(self.storage_path, "r", encoding="utf-8") as f:
|
with self.storage_path.open("r", encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
|
if not isinstance(data, list):
|
||||||
|
raise ValueError("memory file must contain a JSON list")
|
||||||
for item_data in data:
|
for item_data in data:
|
||||||
item = MemoryItem(**item_data)
|
item = MemoryItem(**item_data)
|
||||||
self._items[item.id] = item
|
self._items[item.id] = item
|
||||||
@@ -41,70 +49,89 @@ class GlobalMemory:
|
|||||||
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
||||||
|
|
||||||
def _save(self) -> None:
|
def _save(self) -> None:
|
||||||
try:
|
|
||||||
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(self.storage_path, "w", encoding="utf-8") as f:
|
payload = json.dumps(
|
||||||
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
|
[asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2
|
||||||
except Exception as e:
|
)
|
||||||
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
|
fd, tmp_name = tempfile.mkstemp(
|
||||||
|
prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||||
|
f.write(payload)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.replace(tmp_name, self.storage_path)
|
||||||
|
# Persist the directory entry as well (important on abrupt shutdown).
|
||||||
|
try:
|
||||||
|
dir_fd = os.open(self.storage_path.parent, os.O_DIRECTORY)
|
||||||
|
try:
|
||||||
|
os.fsync(dir_fd)
|
||||||
|
finally:
|
||||||
|
os.close(dir_fd)
|
||||||
|
except OSError:
|
||||||
|
logger.debug("Directory fsync is unavailable for %s", self.storage_path.parent)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
os.unlink(tmp_name)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
||||||
"""Add a new fact or preference to global memory."""
|
|
||||||
item_id = str(uuid.uuid4())[:8]
|
item_id = str(uuid.uuid4())[:8]
|
||||||
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
||||||
self._items[item_id] = item
|
self._items[item_id] = item
|
||||||
|
try:
|
||||||
self._save()
|
self._save()
|
||||||
|
except OSError as e:
|
||||||
|
logger.error("Failed to persist global memory to %s: %s", self.storage_path, e)
|
||||||
|
raise
|
||||||
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
|
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
|
||||||
return item
|
return item
|
||||||
|
|
||||||
def remove_fact(self, fact_id: str) -> bool:
|
def remove_fact(self, fact_id: str) -> bool:
|
||||||
"""Remove a fact by its ID."""
|
if fact_id not in self._items:
|
||||||
if fact_id in self._items:
|
return False
|
||||||
del self._items[fact_id]
|
del self._items[fact_id]
|
||||||
self._save()
|
self._save()
|
||||||
return True
|
return True
|
||||||
return False
|
|
||||||
|
|
||||||
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
||||||
"""List all facts, optionally filtered by category."""
|
|
||||||
if category:
|
if category:
|
||||||
cat = category.strip().lower()
|
cat = category.strip().lower()
|
||||||
return [item for item in self._items.values() if item.category == cat]
|
return [item for item in self._items.values() if item.category == cat]
|
||||||
return list(self._items.values())
|
return list(self._items.values())
|
||||||
|
|
||||||
def search(self, query: str) -> list[MemoryItem]:
|
def search(self, query: str) -> list[MemoryItem]:
|
||||||
"""Search memory for keywords in query."""
|
|
||||||
q = query.lower()
|
q = query.lower()
|
||||||
return [
|
return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
|
||||||
item for item in self._items.values()
|
|
||||||
if q in item.fact.lower() or q in item.category.lower()
|
|
||||||
]
|
|
||||||
|
|
||||||
def clear(self) -> None:
|
def clear(self) -> None:
|
||||||
"""Clear all stored memory."""
|
|
||||||
self._items.clear()
|
self._items.clear()
|
||||||
self._save()
|
self._save()
|
||||||
|
|
||||||
def get_memory_summary(self, max_items: int = 30) -> str:
|
def get_memory_summary(self, max_items: int = 30) -> str:
|
||||||
"""Produce a formatted summary of remembered facts for the system prompt."""
|
|
||||||
if not self._items:
|
if not self._items:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||||
items = list(self._items.values())[-max_items:]
|
for item in list(self._items.values())[-max_items:]:
|
||||||
for item in items:
|
|
||||||
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
# Singleton instance container
|
_global_memory_instances: dict[Path, GlobalMemory] = {}
|
||||||
_global_memory_instance: Optional[GlobalMemory] = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
||||||
global _global_memory_instance
|
"""Return the memory store for the requested persistent path.
|
||||||
if _global_memory_instance is None:
|
|
||||||
|
The cache is keyed by the resolved path, preventing one process/test/config
|
||||||
|
from accidentally reusing memory loaded from another DATA_DIR.
|
||||||
|
"""
|
||||||
if storage_path is None:
|
if storage_path is None:
|
||||||
storage_path = Path("data") / "global_memory.json"
|
storage_path = Path(os.getenv("DATA_DIR", "data")) / "global_memory.json"
|
||||||
_global_memory_instance = GlobalMemory(storage_path)
|
path = Path(storage_path).expanduser().resolve()
|
||||||
return _global_memory_instance
|
if path not in _global_memory_instances:
|
||||||
|
_global_memory_instances[path] = GlobalMemory(path)
|
||||||
|
return _global_memory_instances[path]
|
||||||
Reference in new issue
Block a user