Skip to content

The agent that grows with you

refactor(utils): stage every atomic writer's temp through one mkstemp_beside helper

kshitijk4poor4de541df1ad9
diff --git a/cron/jobs.py b/cron/jobs.py
index 513ca5dcc3f..ac9e8944541 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -8,7 +8,6 @@ from dataclasses import dataclass, field
import json
import logging
import shutil
-import tempfile
import threading
import time
import os
@@ -37,7 +36,7 @@ logger = logging.getLogger(__name__)
from hermes_time import now as _hermes_now
from hermes_time import get_timezone
from hermes_cli.observability.shared_metrics_gateway import record_cron_missed
-from utils import atomic_replace, atomic_write_text, fsync_directory
+from utils import atomic_replace, atomic_write_text, fsync_directory, mkstemp_beside
# croniter is imported lazily (slow import, only needed for cron exprs). HAS_CRONITER stays a
# module attribute: a monkeypatched value wins because _ensure_croniter only probes while None.
@@ -1534,16 +1533,8 @@ def _unlink_quiet(path: Optional[str]) -> None:
def _stage_jobs_payload(jobs_file: Path, jobs: List[Dict[str, Any]]) -> str:
- """Serialize the store payload to a fsynced temp file beside the RESOLVED *jobs_file*; return
- its path. A temp next to a symlink whose target is on another filesystem makes the rename
- EXDEV, and atomic_replace's copy fallback then rewrites the store in place (torn on crash)."""
- try:
- fd, tmp_path = tempfile.mkstemp(
- dir=os.path.dirname(os.path.realpath(jobs_file)), suffix=".tmp", prefix=".jobs_")
- except PermissionError:
- # The link target's directory may be read-only to us while the file itself is writable;
- # staging beside the link keeps saves working (non-atomic copy fallback, as before).
- fd, tmp_path = tempfile.mkstemp(dir=str(jobs_file.parent), suffix=".tmp", prefix=".jobs_")
+ """Serialize the store payload to a fsynced temp file beside the resolved *jobs_file*; return its path."""
+ fd, tmp_path = mkstemp_beside(jobs_file, suffix=".tmp", prefix=".jobs_")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(
diff --git a/hermes_cli/backup_restore.py b/hermes_cli/backup_restore.py
index 18bd43d9b0f..da51878f00a 100644
--- a/hermes_cli/backup_restore.py
+++ b/hermes_cli/backup_restore.py
@@ -21,6 +21,7 @@ from typing import List, Optional, Tuple
from hermes_state_holders import read_only_db_uri
from utils import (
_preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,
+ mkstemp_beside,
)
logger = logging.getLogger(__name__)
@@ -344,11 +345,8 @@ def _extract_member_atomically(
mode &= ~(stat.S_ISUID | stat.S_ISGID)
# Truncate the stem: mkstemp adds ~16 characters, and a member already near
- # NAME_MAX would otherwise fail here on a write that used to succeed. Stage beside the
- # RESOLVED target so a symlinked member renames atomically instead of an EXDEV in-place copy.
- fd, tmp_name = tempfile.mkstemp(
- dir=os.path.dirname(os.path.realpath(target)), prefix=f".{target.name[:80]}.", suffix=".partial"
- )
+ # NAME_MAX would otherwise fail here on a write that used to succeed.
+ fd, tmp_name = mkstemp_beside(target, prefix=f".{target.name[:80]}.", suffix=".partial")
try:
with os.fdopen(fd, "wb") as dst:
if mode is not None:
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index bc3b43d14f0..49a2980a30e 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -46,7 +46,7 @@ from hermes_constants import ( # noqa: F401
apply_secure_dir_policy, get_managed_system)
# Re-export from hermes_constants — canonical definition lives there.
from hermes_constants import get_hermes_home, get_process_hermes_home # noqa: F401
-from utils import atomic_replace, fast_safe_load, file_signature
+from utils import atomic_replace, fast_safe_load, file_signature, mkstemp_beside
from hermes_cli.config_read_errors import (
_CONFIG_PARSE_FAILURES, _FIX_PERMS, _FIX_YAML, FailedConfigRead, _backups_dir_display,
_refuse_failed_read, _refuse_overwrite, _warn_config_parse_failure, _yaml_error_details,
@@ -2628,8 +2628,7 @@ def _write_env_lines(env_path: Path, lines: list, *, preserve_mode: bool) -> Non
original_mode = stat.S_IMODE(env_path.stat().st_mode) if preserve_mode else None
except OSError:
pass
- # Beside the resolved target so a symlinked .env still renames atomically (no EXDEV copy).
- fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(os.path.realpath(env_path)), suffix=".tmp", prefix=".env_")
+ fd, tmp_path = mkstemp_beside(env_path, suffix=".tmp", prefix=".env_")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.writelines(lines)
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index a9b687cecbb..ea62dc8e4fe 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -15,7 +15,7 @@ from pathlib import Path
# wiped (#57828) so early recovery provably runs before third-party imports (test_early_recovery).
# The parser internals are imported lazily below because gateway tests stub ``sys.modules["dotenv"]``.
import dotenv # noqa: F401
-from utils import atomic_replace, load_yaml_file_readonly
+from utils import atomic_replace, load_yaml_file_readonly, mkstemp_beside
logger = logging.getLogger(__name__)
@@ -435,9 +435,7 @@ def _sanitize_env_file_if_needed(path: Path) -> None:
stripped = [line.replace("\x00", "") for line in original]
sanitized = _sanitize_env_lines(stripped)
if sanitized != original or force_utf8_rewrite:
- import tempfile
- # Beside the resolved target so a symlinked .env still renames atomically (no EXDEV copy).
- fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.realpath(path)), suffix=".tmp", prefix=".env_")
+ fd, tmp = mkstemp_beside(path, suffix=".tmp", prefix=".env_")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.writelines(sanitized)
diff --git a/utils.py b/utils.py
index 57177e6193e..ac15080fe16 100644
--- a/utils.py
+++ b/utils.py
@@ -206,6 +206,26 @@ def atomic_replace(tmp_path: Union[str, Path], target: Union[str, Path]) -> str:
return real_path
+def mkstemp_beside(target: Union[str, Path], **kw: Any) -> tuple[int, str]:
+ """``tempfile.mkstemp`` in the directory :func:`atomic_replace` will rename into.
+
+ A temp staged next to a symlink whose target lives on another filesystem turns the publish
+ rename into EXDEV, and atomic_replace's copy fallback then rewrites the file in place (torn on
+ a crash). Staging beside the resolved target keeps the rename atomic. If that directory is not
+ writable to us (the file itself may still be), stage beside the link instead: the save keeps
+ working through the non-atomic copy fallback, exactly as before.
+ """
+ target_str = str(target)
+ link_dir = str(Path(target_str).parent)
+ stage_dir = os.path.dirname(os.path.realpath(target_str)) if os.path.islink(target_str) else link_dir
+ try:
+ return tempfile.mkstemp(dir=stage_dir, **kw)
+ except PermissionError:
+ if stage_dir == link_dir:
+ raise
+ return tempfile.mkstemp(dir=link_dir, **kw)
+
+
def fsync_directory(path: Union[str, Path]) -> None:
"""Best-effort fsync of a directory entry so a just-renamed file survives power loss.
@@ -286,9 +306,7 @@ def _atomic_write(path: Path, write, *, prefix: str, encoding: str = "utf-8", mo
if mode is None and not path.exists():
mode = default_new_file_mode()
original_owner = _preserve_file_owner(path) if preserve_owner else None
- # Stage beside the RESOLVED target: a temp next to a symlink into another filesystem turns the
- # rename into EXDEV and atomic_replace falls back to a tearable in-place copy.
- fd, tmp_path = tempfile.mkstemp(dir=str(Path(os.path.realpath(path)).parent), prefix=prefix, suffix=".tmp")
+ fd, tmp_path = mkstemp_beside(path, prefix=prefix, suffix=".tmp")
try:
with os.fdopen(fd, "wb" if binary else "w", encoding=None if binary else encoding) as f:
if mode is not None and hasattr(os, "fchmod"):