fix(agent): use atomic write in _save_session_log to prevent data loss
This commit is contained in:
parent
486cb772b8
commit
f685741481
1 changed files with 12 additions and 2 deletions
14
run_agent.py
14
run_agent.py
|
|
@ -28,6 +28,7 @@ import json
|
||||||
import logging
|
import logging
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
import os
|
import os
|
||||||
|
import tempfile
|
||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
|
|
@ -1398,8 +1399,17 @@ class AIAgent:
|
||||||
"messages": cleaned,
|
"messages": cleaned,
|
||||||
}
|
}
|
||||||
|
|
||||||
with open(self.session_log_file, "w", encoding="utf-8") as f:
|
tmp_dir = str(self.session_log_file.parent) if hasattr(self.session_log_file, 'parent') else os.path.dirname(str(self.session_log_file))
|
||||||
json.dump(entry, f, indent=2, ensure_ascii=False, default=str)
|
fd, tmp_path = tempfile.mkstemp(dir=tmp_dir, suffix='.tmp', prefix='.session_')
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(entry, f, indent=2, ensure_ascii=False, default=str)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.replace(tmp_path, str(self.session_log_file))
|
||||||
|
except:
|
||||||
|
os.unlink(tmp_path)
|
||||||
|
raise
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if self.verbose_logging:
|
if self.verbose_logging:
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue