From 9ee18699fd1b3a5d7180a3bee54290f3ab8400c4 Mon Sep 17 00:00:00 2001 From: voidborne-d Date: Fri, 17 Apr 2026 19:06:36 +0000 Subject: [PATCH] refactor: improve _load() efficiency and _save() error handling - Populate lists directly in _load() to avoid redundant _save() call - Add try/except OSError in _save() for graceful degradation - Expand _load() exception handling with AttributeError, TypeError Addresses code review feedback from gemini-code-assist. --- tradingagents/agents/utils/memory.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/tradingagents/agents/utils/memory.py b/tradingagents/agents/utils/memory.py index 94982d21..970ce245 100644 --- a/tradingagents/agents/utils/memory.py +++ b/tradingagents/agents/utils/memory.py @@ -65,11 +65,13 @@ class FinancialSituationMemory: data = json.loads(self._persist_path.read_text(encoding="utf-8")) situations = data.get("situations", []) recommendations = data.get("recommendations", []) - # Pair them up; ignore mismatched trailing entries - pairs = list(zip(situations, recommendations)) - if pairs: - self.add_situations(pairs) - except (json.JSONDecodeError, OSError): + # Populate lists directly to avoid redundant _save() call + for situation, recommendation in zip(situations, recommendations): + self.documents.append(situation) + self.recommendations.append(recommendation) + if self.documents: + self._rebuild_index() + except (json.JSONDecodeError, OSError, AttributeError, TypeError): # Corrupt / unreadable file — start fresh pass @@ -81,10 +83,14 @@ class FinancialSituationMemory: "situations": list(self.documents), "recommendations": list(self.recommendations), } - # Atomic-ish write: write to temp then rename - tmp = self._persist_path.with_suffix(".tmp") - tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") - tmp.replace(self._persist_path) + try: + # Atomic-ish write: write to temp then rename + tmp = self._persist_path.with_suffix(".tmp") + tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") + tmp.replace(self._persist_path) + except OSError: + # Fail gracefully if disk is full or permissions are restricted + pass # ------------------------------------------------------------------ # Tokenisation & indexing