refactor(utils): dedupe atomic JSONL write helper
Extract atomic_write_lines so history.jsonl, session JSONL saves, and WebUI transcript rewrites share unique temp files, optional fsync, and BaseException cleanup. Closes #5290
This commit is contained in:
1 parent
27b3e81434
commit
23de1f1e34
7 files changed
+287
-89
No files matched your search
+5
-23
@@ -9,7 +9,6 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import weakref
|
||||
@@ -31,6 +30,7 @@ from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata
|
||||
from nanobot.utils.gitstore import GitStore
|
||||
from nanobot.utils.helpers import (
|
||||
atomic_write_lines,
|
||||
build_assistant_message,
|
||||
content_with_media_breadcrumbs,
|
||||
ensure_dir,
|
||||
@@ -473,28 +473,10 @@ class MemoryStore:
|
||||
|
||||
def _write_entries(self, entries: list[dict[str, Any]]) -> None:
|
||||
"""Overwrite history.jsonl with the given entries (atomic write)."""
|
||||
tmp_path = self.history_file.with_suffix(self.history_file.suffix + ".tmp")
|
||||
try:
|
||||
with open(tmp_path, "w", encoding="utf-8") as f:
|
||||
for entry in entries:
|
||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp_path, self.history_file)
|
||||
|
||||
# fsync the directory so the rename is durable.
|
||||
# On Windows, opening a directory with O_RDONLY raises
|
||||
# PermissionError — skip the dir sync there (NTFS
|
||||
# journals metadata synchronously).
|
||||
with suppress(PermissionError):
|
||||
fd = os.open(str(self.history_file.parent), os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
except BaseException:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
atomic_write_lines(
|
||||
self.history_file,
|
||||
(json.dumps(entry, ensure_ascii=False) for entry in entries),
|
||||
)
|
||||
|
||||
# -- dream cursor --------------------------------------------------------
|
||||
|
||||
|
||||
+27
-45
@@ -31,6 +31,7 @@ from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_hi
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT, is_summary_checkpoint
|
||||
from nanobot.utils.helpers import (
|
||||
atomic_write_lines,
|
||||
content_with_media_breadcrumbs,
|
||||
ensure_dir,
|
||||
estimate_message_tokens,
|
||||
@@ -1205,52 +1206,33 @@ class JsonlSessionStore:
|
||||
|
||||
def _save_unlocked(self, session: Session, *, fsync: bool = False) -> None:
|
||||
path = self.get_session_path(session.key)
|
||||
tmp_path = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
|
||||
metadata_line = {
|
||||
"_type": "metadata",
|
||||
"key": session.key,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"updated_at": session.updated_at.isoformat(),
|
||||
"metadata": session.metadata,
|
||||
"last_archived": session.last_archived,
|
||||
# Keep old nanobot releases able to read sessions written
|
||||
# during the field-name migration.
|
||||
"last_consolidated": session.last_consolidated,
|
||||
}
|
||||
lines = [json.dumps(metadata_line, ensure_ascii=False)]
|
||||
if session.provider_state is not None:
|
||||
provider_state_line = {
|
||||
"_type": _PROVIDER_STATE_RECORD_TYPE,
|
||||
"state": session.provider_state.to_private_record(),
|
||||
}
|
||||
lines.append(json.dumps(provider_state_line, ensure_ascii=False))
|
||||
for msg in session.messages:
|
||||
lines.append(json.dumps(msg, ensure_ascii=False))
|
||||
# fsync=False keeps the historical session-save default: publish the
|
||||
# file without file or directory fsync unless the caller opts in.
|
||||
atomic_write_lines(path, lines, fsync=fsync)
|
||||
|
||||
try:
|
||||
with open(tmp_path, "x", encoding="utf-8") as f:
|
||||
metadata_line = {
|
||||
"_type": "metadata",
|
||||
"key": session.key,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"updated_at": session.updated_at.isoformat(),
|
||||
"metadata": session.metadata,
|
||||
"last_archived": session.last_archived,
|
||||
# Keep old nanobot releases able to read sessions written
|
||||
# during the field-name migration.
|
||||
"last_consolidated": session.last_consolidated,
|
||||
}
|
||||
f.write(json.dumps(metadata_line, ensure_ascii=False) + "\n")
|
||||
if session.provider_state is not None:
|
||||
provider_state_line = {
|
||||
"_type": _PROVIDER_STATE_RECORD_TYPE,
|
||||
"state": session.provider_state.to_private_record(),
|
||||
}
|
||||
f.write(json.dumps(provider_state_line, ensure_ascii=False) + "\n")
|
||||
for msg in session.messages:
|
||||
f.write(json.dumps(msg, ensure_ascii=False) + "\n")
|
||||
if fsync:
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
|
||||
os.replace(tmp_path, path)
|
||||
|
||||
# The full record now contains the authoritative checkpoint state (or
|
||||
# its removal), so an older volatile overlay is no longer needed.
|
||||
self.get_runtime_checkpoint_path(session.key).unlink(missing_ok=True)
|
||||
|
||||
if fsync:
|
||||
with suppress(PermissionError):
|
||||
fd = os.open(str(path.parent), os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EINVAL:
|
||||
raise
|
||||
finally:
|
||||
os.close(fd)
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
# The full record now contains the authoritative checkpoint state (or
|
||||
# its removal), so an older volatile overlay is no longer needed.
|
||||
self.get_runtime_checkpoint_path(session.key).unlink(missing_ok=True)
|
||||
|
||||
def update_metadata(
|
||||
self,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -10,6 +11,7 @@ import shutil
|
||||
import stat
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Iterable
|
||||
from contextlib import suppress
|
||||
from datetime import datetime
|
||||
from functools import lru_cache
|
||||
@@ -552,6 +554,54 @@ def _cleanup_tool_result_buckets(root: Path, current_bucket: Path) -> None:
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
|
||||
def atomic_write_lines(path: Path, lines: Iterable[str], *, fsync: bool = True) -> None:
|
||||
"""Atomically replace *path* with already-serialized record lines.
|
||||
|
||||
Each item is one record. A trailing newline is added when the item does
|
||||
not already end with one. The bytes are written to a uniquely named temp
|
||||
file in the same directory, then published with ``os.replace``.
|
||||
|
||||
``fsync=True`` (the default) flushes and fsyncs the file before the
|
||||
replace, then fsyncs the parent directory. ``fsync=False`` skips both,
|
||||
which session saves use when the caller does not ask for durability.
|
||||
Directory fsync suppresses ``PermissionError`` (Windows cannot open a
|
||||
directory this way) and ``EINVAL`` (filesystems that reject directory
|
||||
fsync). Any other directory fsync error propagates. The temp file is
|
||||
removed on every ``BaseException``.
|
||||
|
||||
#5291's subagent transcript store should call this helper when it merges
|
||||
instead of copying the temp/fsync/replace sequence.
|
||||
"""
|
||||
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
with open(tmp, "x", encoding="utf-8") as handle:
|
||||
for line in lines:
|
||||
handle.write(line if line.endswith("\n") else f"{line}\n")
|
||||
if fsync:
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(tmp, path)
|
||||
if fsync:
|
||||
_fsync_directory_after_replace(path.parent)
|
||||
finally:
|
||||
if tmp.exists():
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _fsync_directory_after_replace(directory: Path) -> None:
|
||||
"""Fsync *directory* after a replace, ignoring unsupported platforms."""
|
||||
with suppress(PermissionError):
|
||||
fd = os.open(str(directory), os.O_RDONLY)
|
||||
try:
|
||||
try:
|
||||
os.fsync(fd)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EINVAL:
|
||||
raise
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _write_text_atomic(path: Path, content: str) -> None:
|
||||
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
existing_mode: int | None = None
|
||||
|
||||
@@ -24,6 +24,7 @@ from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.automation_turns import is_automation_kind
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.utils.helpers import atomic_write_lines
|
||||
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
|
||||
from nanobot.webui.session_identity import webui_chat_id, webui_session_key
|
||||
|
||||
@@ -443,20 +444,13 @@ def _records_with_replay_identity(
|
||||
|
||||
def _write_records_to_path(path: Path, rows: list[dict[str, Any]]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = path.with_suffix(path.suffix + ".tmp")
|
||||
try:
|
||||
with open(tmp_path, "w", encoding="utf-8") as f:
|
||||
for row in rows:
|
||||
raw = _record_json_line(row)
|
||||
if len(raw.encode("utf-8")) > _MAX_TRANSCRIPT_FILE_BYTES:
|
||||
raise ValueError("webui transcript line too large")
|
||||
f.write(raw + "\n")
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp_path, path)
|
||||
except BaseException:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
lines: list[str] = []
|
||||
for row in rows:
|
||||
raw = _record_json_line(row)
|
||||
if len(raw.encode("utf-8")) > _MAX_TRANSCRIPT_FILE_BYTES:
|
||||
raise ValueError("webui transcript line too large")
|
||||
lines.append(raw)
|
||||
atomic_write_lines(path, lines)
|
||||
|
||||
|
||||
def _segment_file_path(session_key: str, segment_id: str) -> Path:
|
||||
|
||||
Reference in new issue
Block a user