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.
This commit is contained in:
parent
1e2164ec78
commit
9ee18699fd
|
|
@ -65,11 +65,13 @@ class FinancialSituationMemory:
|
||||||
data = json.loads(self._persist_path.read_text(encoding="utf-8"))
|
data = json.loads(self._persist_path.read_text(encoding="utf-8"))
|
||||||
situations = data.get("situations", [])
|
situations = data.get("situations", [])
|
||||||
recommendations = data.get("recommendations", [])
|
recommendations = data.get("recommendations", [])
|
||||||
# Pair them up; ignore mismatched trailing entries
|
# Populate lists directly to avoid redundant _save() call
|
||||||
pairs = list(zip(situations, recommendations))
|
for situation, recommendation in zip(situations, recommendations):
|
||||||
if pairs:
|
self.documents.append(situation)
|
||||||
self.add_situations(pairs)
|
self.recommendations.append(recommendation)
|
||||||
except (json.JSONDecodeError, OSError):
|
if self.documents:
|
||||||
|
self._rebuild_index()
|
||||||
|
except (json.JSONDecodeError, OSError, AttributeError, TypeError):
|
||||||
# Corrupt / unreadable file — start fresh
|
# Corrupt / unreadable file — start fresh
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
@ -81,10 +83,14 @@ class FinancialSituationMemory:
|
||||||
"situations": list(self.documents),
|
"situations": list(self.documents),
|
||||||
"recommendations": list(self.recommendations),
|
"recommendations": list(self.recommendations),
|
||||||
}
|
}
|
||||||
# Atomic-ish write: write to temp then rename
|
try:
|
||||||
tmp = self._persist_path.with_suffix(".tmp")
|
# Atomic-ish write: write to temp then rename
|
||||||
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
tmp = self._persist_path.with_suffix(".tmp")
|
||||||
tmp.replace(self._persist_path)
|
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
|
# Tokenisation & indexing
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue