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:
Frank_zhu authored and chengyongru committed 2026-09-23 14:48:29 +08:00
1 parent 27b3e81434
commit 23de1f1e34
7 files changed
+287 -89

No files matched your search

+50
View File
@@ -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