refactor: deduplicate durable writes and file-edit path resolution

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-14 14:12:48 +08:00
1 parent 4497f7ef24
commit 74b22b6522
6 files changed
+70 -115

No files matched your search

+3 -36
View File
@@ -1,9 +1,7 @@
"""Cron service for scheduling agent tasks."""
import asyncio
import errno
import json
import os
import time
import uuid
from contextlib import suppress
@@ -29,6 +27,7 @@ from nanobot.cron.types import (
CronStore,
)
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META
from nanobot.utils.helpers import atomic_write_text
from nanobot.utils.run_records import (
write_run_record as write_automation_run_record,
)
@@ -447,40 +446,8 @@ class CronService:
@staticmethod
def _atomic_write(path: Path, content: str) -> None:
"""Write *content* to *path* atomically with fsync.
Uses a temp-file + ``os.replace`` + ``fsync`` pattern so a crash or
SIGKILL mid-write cannot leave the destination truncated or invalid.
Mirrors ``nanobot.session.manager.SessionManager.save`` (see
commit 512bf59, ``fix(session): fsync sessions on graceful shutdown
to prevent data loss``). Without this, ``jobs.json`` could be
corrupted on container shutdown and silently re-created empty on
next start, wiping every scheduled job.
"""
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:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
# fsync the parent directory so the rename itself is durable.
# Skip on Windows where opening a directory raises PermissionError;
# some shared filesystems reject directory fsync with EINVAL.
with suppress(PermissionError):
fd = os.open(str(path.parent), os.O_RDONLY)
try:
try:
os.fsync(fd)
except OSError as exc:
if exc.errno != errno.EINVAL:
raise
finally:
os.close(fd)
except BaseException:
tmp_path.unlink(missing_ok=True)
raise
"""Durably replace the job store without exposing a partial write."""
atomic_write_text(path, content)
def write_run_record(self, run_id: str, record: dict[str, Any]) -> None:
"""Write an internal audit record for one cron execution."""
+2 -23
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import errno
import json
import os
import secrets
@@ -16,7 +15,7 @@ from filelock import FileLock
from loguru import logger
from nanobot.triggers.local_types import LocalTrigger, TriggerDelivery, TriggerRunRecord
from nanobot.utils.helpers import truncate_text
from nanobot.utils.helpers import atomic_write_text, truncate_text
from nanobot.utils.run_records import write_run_record as write_automation_run_record
_TRIGGER_ID_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
@@ -409,27 +408,7 @@ class LocalTriggerStore:
@staticmethod
def _atomic_write(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
try:
with open(tmp_path, "w", encoding="utf-8") as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
with suppress(PermissionError):
fd = os.open(str(path.parent), os.O_RDONLY)
try:
try:
os.fsync(fd)
except OSError as exc:
if exc.errno != errno.EINVAL:
raise
finally:
os.close(fd)
except BaseException:
tmp_path.unlink(missing_ok=True)
raise
atomic_write_text(path, content)
def _new_trigger_id(existing_ids: set[str]) -> str:
+11 -20
View File
@@ -410,26 +410,17 @@ def _resolve_apply_patch_paths(
def _resolve_single_path(tool: Any, workspace: Path | None, raw_path: Any) -> Path | None:
if not isinstance(raw_path, str) or not raw_path.strip():
return None
resolver = getattr(tool, "_resolve_write", None)
if callable(resolver):
try:
resolved = resolver(raw_path)
if isinstance(resolved, Path):
return resolved
if resolved:
return Path(cast(str, resolved))
except Exception:
return None
resolver = getattr(tool, "_resolve", None)
if callable(resolver):
try:
resolved = resolver(raw_path)
if isinstance(resolved, Path):
return resolved
if resolved:
return Path(cast(str, resolved))
except Exception:
return None
for resolver_name in ("_resolve_write", "_resolve"):
resolver = getattr(tool, resolver_name, None)
if callable(resolver):
try:
resolved = resolver(raw_path)
if isinstance(resolved, Path):
return resolved
if resolved:
return Path(cast(str, resolved))
except Exception:
return None
if workspace is None:
return Path(raw_path).expanduser().resolve()
return (workspace / raw_path).expanduser().resolve()
+16
View File
@@ -547,6 +547,22 @@ def _cleanup_tool_result_buckets(root: Path, current_bucket: Path) -> None:
shutil.rmtree(path, ignore_errors=True)
def atomic_write_text(path: Path, content: str) -> None:
"""Create parent directories and durably replace *path* with UTF-8 text."""
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
try:
with open(tmp_path, "w", encoding="utf-8") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, path)
_fsync_directory_after_replace(path.parent)
except BaseException:
tmp_path.unlink(missing_ok=True)
raise
def atomic_write_lines(path: Path, lines: Iterable[str], *, fsync: bool = True) -> None:
"""Atomically replace *path* with already-serialized record lines.
+3 -28
View File
@@ -2,15 +2,14 @@
from __future__ import annotations
import errno
import json
import os
import time
import uuid
from contextlib import suppress
from pathlib import Path
from typing import Any
from nanobot.utils.helpers import atomic_write_text
def safe_run_record_name(run_id: str) -> str:
"""Return a filesystem-safe filename stem for a run ID."""
@@ -26,33 +25,9 @@ def write_run_record(runs_dir: Path, run_id: str, record: dict[str, Any]) -> Pat
"run_id": run_id,
"updated_at_ms": _now_ms(),
}
_atomic_write(path, json.dumps(payload, indent=2, ensure_ascii=False))
atomic_write_text(path, json.dumps(payload, indent=2, ensure_ascii=False))
return path
def _now_ms() -> int:
return int(time.time() * 1000)
def _atomic_write(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
try:
with open(tmp_path, "w", encoding="utf-8") as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
with suppress(PermissionError):
fd = os.open(str(path.parent), os.O_RDONLY)
try:
try:
os.fsync(fd)
except OSError as exc:
if exc.errno != errno.EINVAL:
raise
finally:
os.close(fd)
except BaseException:
tmp_path.unlink(missing_ok=True)
raise