diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.py index 2ab35de5e..70467481d 100644 --- a/nanobot/agent/memory.py +++ b/nanobot/agent/memory.py @@ -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 -------------------------------------------------------- diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index a4035fd99..8def6f41d 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -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, diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.py index 0164c5b23..888fd49e2 100644 --- a/nanobot/utils/helpers.py +++ b/nanobot/utils/helpers.py @@ -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 diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 78912424c..3a5b61d88 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -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: diff --git a/tests/agent/test_memory_store.py b/tests/agent/test_memory_store.py index 276eb3372..0aaaecd3b 100644 --- a/tests/agent/test_memory_store.py +++ b/tests/agent/test_memory_store.py @@ -241,8 +241,9 @@ class TestHistoryWithCursor: with pytest.raises(RuntimeError): store._write_entries(entries) - # Temp file should be cleaned up + # Temp file should be cleaned up, including uniquely named temps. assert not tmp_path_obj.exists() + assert list(store.history_file.parent.glob("*.tmp")) == [] # Original file should still exist (because replace failed) assert store.history_file.exists() diff --git a/tests/session/test_session_fsync.py b/tests/session/test_session_fsync.py index 5719c2fc2..8a602b57d 100644 --- a/tests/session/test_session_fsync.py +++ b/tests/session/test_session_fsync.py @@ -66,12 +66,12 @@ class TestSaveFsync: directory_fd = 987654 with ( manager.locked_session_files(), - patch("nanobot.session.manager.os.open", return_value=directory_fd) as open_dir, + patch("nanobot.utils.helpers.os.open", return_value=directory_fd) as open_dir, patch( - "nanobot.session.manager.os.fsync", + "nanobot.utils.helpers.os.fsync", side_effect=[None, OSError(errno.EINVAL, "Invalid argument")], ), - patch("nanobot.session.manager.os.close") as close_dir, + patch("nanobot.utils.helpers.os.close") as close_dir, ): manager.save(session, fsync=True) @@ -87,12 +87,12 @@ class TestSaveFsync: directory_fd = 987654 with ( manager.locked_session_files(), - patch("nanobot.session.manager.os.open", return_value=directory_fd), + patch("nanobot.utils.helpers.os.open", return_value=directory_fd), patch( - "nanobot.session.manager.os.fsync", + "nanobot.utils.helpers.os.fsync", side_effect=[None, OSError(errno.EIO, "I/O error")], ), - patch("nanobot.session.manager.os.close") as close_dir, + patch("nanobot.utils.helpers.os.close") as close_dir, pytest.raises(OSError, match="I/O error"), ): manager.save(session, fsync=True) diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.py index 0a7a10338..75141bc59 100644 --- a/tests/utils/test_helpers.py +++ b/tests/utils/test_helpers.py @@ -1,10 +1,14 @@ +import errno +import os from pathlib import Path +import pytest import tiktoken from nanobot.utils import helpers from nanobot.utils.helpers import ( _write_text_atomic, + atomic_write_lines, content_with_media_breadcrumbs, split_message, truncate_text_to_tokens, @@ -185,3 +189,188 @@ def test_write_text_atomic_keeps_file_when_directory_fsync_is_unsupported( assert target.read_text(encoding="utf-8") == '{"pending": {}}' assert len(fsync_calls) == 1 + + +def test_atomic_write_lines_round_trip_replaces_target(tmp_path: Path) -> None: + """Missing newline insertion or a non-atomic partial write drops records.""" + target = tmp_path / "history.jsonl" + target.write_text("old\n", encoding="utf-8") + + atomic_write_lines(target, ['{"a": 1}', "café"]) + + assert target.read_text(encoding="utf-8") == '{"a": 1}\ncafé\n' + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_atomic_write_lines_empty_input_replaces_file_with_empty(tmp_path: Path) -> None: + target = tmp_path / "history.jsonl" + target.write_text("old\n", encoding="utf-8") + + atomic_write_lines(target, []) + + assert target.read_text(encoding="utf-8") == "" + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_atomic_write_lines_cleans_temp_when_replace_fails( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failed replace must not leave a temp file or change the target.""" + target = tmp_path / "history.jsonl" + target.write_text("kept\n", encoding="utf-8") + + def fail_replace(*_args: object, **_kwargs: object) -> None: + raise RuntimeError("replace failed") + + monkeypatch.setattr(helpers.os, "replace", fail_replace) + + with pytest.raises(RuntimeError, match="replace failed"): + atomic_write_lines(target, ["new"]) + + assert target.read_text(encoding="utf-8") == "kept\n" + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_atomic_write_lines_cleans_temp_on_base_exception( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """KeyboardInterrupt during replace still removes the temp file.""" + target = tmp_path / "history.jsonl" + target.write_text("kept\n", encoding="utf-8") + + def interrupt(*_args: object, **_kwargs: object) -> None: + raise KeyboardInterrupt + + monkeypatch.setattr(helpers.os, "replace", interrupt) + + with pytest.raises(KeyboardInterrupt): + atomic_write_lines(target, ["new"]) + + assert target.read_text(encoding="utf-8") == "kept\n" + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_atomic_write_lines_leaves_unrelated_tmp_sibling(tmp_path: Path) -> None: + """A unique temp name must not clobber a sibling ``*.tmp`` file.""" + target = tmp_path / "history.jsonl" + stale = target.with_name(target.name + ".tmp") + stale.write_text("stale", encoding="utf-8") + + atomic_write_lines(target, ["fresh"]) + + assert target.read_text(encoding="utf-8") == "fresh\n" + assert stale.read_text(encoding="utf-8") == "stale" + + +def test_atomic_write_lines_skips_fsync_when_disabled( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + target = tmp_path / "session.jsonl" + fsync_calls: list[int] = [] + monkeypatch.setattr(helpers.os, "fsync", lambda fd: fsync_calls.append(fd)) + + atomic_write_lines(target, ["line"], fsync=False) + + assert target.read_text(encoding="utf-8") == "line\n" + assert fsync_calls == [] + + +def test_atomic_write_lines_suppresses_directory_permission_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Windows directory open raises PermissionError; the replace must still stick.""" + target = tmp_path / "history.jsonl" + opened: list[tuple[object, int]] = [] + real_open = helpers.os.open + + def open_directory(path: object, flags: int, *args: object, **kwargs: object) -> int: + opened.append((path, flags)) + if flags == os.O_RDONLY: + raise PermissionError("directory open denied") + return real_open(path, flags, *args, **kwargs) + + monkeypatch.setattr(helpers.os, "open", open_directory) + + atomic_write_lines(target, ["ok"]) + + assert target.read_text(encoding="utf-8") == "ok\n" + assert opened == [(str(tmp_path), os.O_RDONLY)] + + +def test_atomic_write_lines_suppresses_einval_directory_fsync( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + target = tmp_path / "session.jsonl" + fsync_calls = 0 + real_fsync = helpers.os.fsync + real_open = helpers.os.open + real_close = helpers.os.close + opened: list[int] = [] + closed: list[int] = [] + + def tracking_open(path: object, flags: int, *args: object, **kwargs: object) -> int: + fd = real_open(path, flags, *args, **kwargs) + if flags == os.O_RDONLY: + opened.append(fd) + return fd + + def tracking_close(fd: int) -> None: + closed.append(fd) + real_close(fd) + + def fsync_then_einval(fd: int) -> None: + nonlocal fsync_calls + fsync_calls += 1 + if fsync_calls == 1: + real_fsync(fd) + return + raise OSError(errno.EINVAL, "Invalid argument") + + monkeypatch.setattr(helpers.os, "open", tracking_open) + monkeypatch.setattr(helpers.os, "close", tracking_close) + monkeypatch.setattr(helpers.os, "fsync", fsync_then_einval) + + atomic_write_lines(target, ["ok"]) + + assert target.read_text(encoding="utf-8") == "ok\n" + assert fsync_calls == 2 + assert opened and opened[0] in closed + + +def test_atomic_write_lines_propagates_other_directory_fsync_errors( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + target = tmp_path / "session.jsonl" + fsync_calls = 0 + real_fsync = helpers.os.fsync + real_open = helpers.os.open + real_close = helpers.os.close + opened: list[int] = [] + closed: list[int] = [] + + def tracking_open(path: object, flags: int, *args: object, **kwargs: object) -> int: + fd = real_open(path, flags, *args, **kwargs) + if flags == os.O_RDONLY: + opened.append(fd) + return fd + + def tracking_close(fd: int) -> None: + closed.append(fd) + real_close(fd) + + def fsync_then_eio(fd: int) -> None: + nonlocal fsync_calls + fsync_calls += 1 + if fsync_calls == 1: + real_fsync(fd) + return + raise OSError(errno.EIO, "I/O error") + + monkeypatch.setattr(helpers.os, "open", tracking_open) + monkeypatch.setattr(helpers.os, "close", tracking_close) + monkeypatch.setattr(helpers.os, "fsync", fsync_then_eio) + + with pytest.raises(OSError, match="I/O error"): + atomic_write_lines(target, ["new"]) + + assert opened and opened[0] in closed