fix: persist runtime memory across Docker restarts #3

Merged
timka123 merged 9 commits from fix/persistence-minimal into master 2026-11-13 23:47:48 +03:00
Showing only changes of commit f68dddf162 - Show all commits
+20 -28
View File
@@ -22,12 +22,7 @@ class MemoryItem:
class GlobalMemory: class GlobalMemory:
"""Persistent global memory store shared across all forum topics. """Persistent global memory store shared across all forum topics."""
The target file is replaced only after a complete JSON document has been
written and flushed. This prevents a restart during a write from leaving
a truncated ``global_memory.json``.
"""
def __init__(self, storage_path: Path): def __init__(self, storage_path: Path):
self.storage_path = Path(storage_path).expanduser().resolve() self.storage_path = Path(storage_path).expanduser().resolve()
@@ -40,6 +35,8 @@ class GlobalMemory:
try: try:
with self.storage_path.open("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
@@ -49,15 +46,9 @@ class GlobalMemory:
def _save(self) -> None: def _save(self) -> None:
self.storage_path.parent.mkdir(parents=True, exist_ok=True) self.storage_path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps( payload = json.dumps([asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2)
[asdict(item) for item in self._items.values()],
ensure_ascii=False,
indent=2,
)
fd, temporary_path = tempfile.mkstemp( fd, temporary_path = tempfile.mkstemp(
prefix=f".{self.storage_path.name}.", prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent
suffix=".tmp",
dir=self.storage_path.parent,
) )
try: try:
with os.fdopen(fd, "w", encoding="utf-8") as f: with os.fdopen(fd, "w", encoding="utf-8") as f:
@@ -73,11 +64,10 @@ class GlobalMemory:
raise raise
def add_fact(self, fact: str, category: str = "general") -> MemoryItem: def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
item_id = str(uuid.uuid4())[:8] item = MemoryItem(id=str(uuid.uuid4())[:8], 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
self._save() self._save()
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:
@@ -95,10 +85,7 @@ class GlobalMemory:
def search(self, query: str) -> list[MemoryItem]: def search(self, query: str) -> list[MemoryItem]:
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:
self._items.clear() self._items.clear()
@@ -113,13 +100,18 @@ class GlobalMemory:
return "\n".join(lines) return "\n".join(lines)
_global_memory_instance: Optional[GlobalMemory] = None _global_memory_instances: dict[Path, GlobalMemory] = {}
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory: def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
global _global_memory_instance """Get the memory store keyed by its absolute path.
if _global_memory_instance is None:
DATA_DIR is used in Docker and keeps this store aligned with the mounted
application directory even when the process working directory changes.
"""
if storage_path is None: if storage_path is None:
storage_path = Path("data") / "global_memory.json" storage_path = Path(os.environ.get("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]