| """Atomic, interruption-safe file writers. |
| |
| Every stage output is written to a temporary file in the destination directory, |
| ``fsync``-ed, then atomically renamed over the target with :func:`os.replace`. |
| An interrupted write therefore cannot corrupt an existing valid artifact: the |
| old file is untouched until the rename succeeds. JSONL batches are flushed and |
| ``fsync``-ed once per logical batch, leaving a valid line boundary on crash |
| without a durability syscall for every row. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| import os |
| import tempfile |
| from collections.abc import Iterable, Iterator |
| from pathlib import Path |
| from typing import Any |
|
|
| from .hashing import canonical_json |
|
|
|
|
| class AtomicWriteError(RuntimeError): |
| """Raised when an atomic write cannot be completed.""" |
|
|
|
|
| def _fsync_dir(directory: Path) -> None: |
| """Best-effort fsync of the directory holding renamed files.""" |
| if not directory.exists(): |
| return |
| fd = os.open(str(directory), os.O_RDONLY) |
| try: |
| os.fsync(fd) |
| except OSError: |
| |
| |
| pass |
| finally: |
| os.close(fd) |
|
|
|
|
| def atomic_write_bytes( |
| path: str | Path, |
| data: bytes, |
| *, |
| fsync_dir: bool = True, |
| ) -> None: |
| """Atomically write ``data`` to ``path`` via temp + fsync + rename.""" |
| target = Path(path) |
| target.parent.mkdir(parents=True, exist_ok=True) |
| with tempfile.NamedTemporaryFile( |
| dir=target.parent, |
| prefix=f".{target.name}.", |
| suffix=".tmp", |
| delete=False, |
| ) as tmp_handle: |
| tmp_path = Path(tmp_handle.name) |
| tmp_handle.write(data) |
| tmp_handle.flush() |
| os.fsync(tmp_handle.fileno()) |
| try: |
| os.replace(tmp_path, target) |
| if fsync_dir: |
| _fsync_dir(target.parent) |
| except BaseException: |
| tmp_path.unlink(missing_ok=True) |
| raise |
|
|
|
|
| def atomic_write_text( |
| path: str | Path, |
| text: str, |
| *, |
| encoding: str = "utf-8", |
| fsync_dir: bool = True, |
| ) -> None: |
| """Atomically write ``text`` to ``path``.""" |
| atomic_write_bytes(path, text.encode(encoding), fsync_dir=fsync_dir) |
|
|
|
|
| def atomic_write_json( |
| path: str | Path, |
| obj: Any, |
| *, |
| fsync_dir: bool = True, |
| ) -> None: |
| """Atomically write a single JSON object to ``path`` using canonical JSON.""" |
| atomic_write_text(path, canonical_json(obj) + "\n", fsync_dir=fsync_dir) |
|
|
|
|
| def _encode_jsonl_row(row: Any) -> bytes: |
| return (canonical_json(row) + "\n").encode("utf-8") |
|
|
|
|
| def atomic_write_jsonl( |
| path: str | Path, |
| rows: Iterable[Any], |
| *, |
| fsync_dir: bool = True, |
| ) -> None: |
| """Atomically write an iterable of rows as canonical JSONL.""" |
| buffer = bytearray() |
| for row in rows: |
| buffer += _encode_jsonl_row(row) |
| atomic_write_bytes(path, bytes(buffer), fsync_dir=fsync_dir) |
|
|
|
|
| class JsonlAppender: |
| """Append JSONL records to a file with per-record fsync. |
| |
| Appending never rewrites earlier bytes, so an interrupted append leaves the |
| existing prefix valid. Each record is written and flushed before the next, |
| so a crash loses at most the in-flight record. Call :meth:`close` (or use as |
| a context manager) to fsync the directory once at the end. |
| """ |
|
|
| def __init__(self, path: str | Path, *, fsync_dir: bool = True) -> None: |
| self.path = Path(path) |
| self.path.parent.mkdir(parents=True, exist_ok=True) |
| self._fsync_dir = fsync_dir |
| |
| self._handle = self.path.open("ab") |
|
|
| def append(self, row: Any) -> None: |
| self._handle.write(_encode_jsonl_row(row)) |
| self._handle.flush() |
| os.fsync(self._handle.fileno()) |
|
|
| def extend(self, rows: Iterable[Any]) -> None: |
| """Append one logical batch and fsync once. |
| |
| Reward generation emits many rows together. Fsyncing every individual |
| row made training spend most of its wall time in durability syscalls; |
| a single batch write still leaves a valid JSONL prefix after a crash and |
| checkpoint recovery rolls the batch back as a unit. |
| """ |
|
|
| payload = b"".join(_encode_jsonl_row(row) for row in rows) |
| if not payload: |
| return |
| self._handle.write(payload) |
| self._handle.flush() |
| os.fsync(self._handle.fileno()) |
|
|
| def close(self) -> None: |
| try: |
| self._handle.close() |
| finally: |
| if self._fsync_dir: |
| _fsync_dir(self.path.parent) |
|
|
| def __enter__(self) -> JsonlAppender: |
| return self |
|
|
| def __exit__(self, *exc: object) -> None: |
| self.close() |
|
|
|
|
| def read_jsonl(path: str | Path) -> Iterator[Any]: |
| """Yield parsed JSON objects from a JSONL file, skipping blank lines.""" |
| with Path(path).open("r", encoding="utf-8") as handle: |
| for line in handle: |
| stripped = line.strip() |
| if not stripped: |
| continue |
| yield json.loads(stripped) |
|
|
|
|
| def count_jsonl(path: str | Path) -> int: |
| """Count non-blank lines in a JSONL file without parsing each row.""" |
| count = 0 |
| with Path(path).open("r", encoding="utf-8") as handle: |
| for line in handle: |
| if line.strip(): |
| count += 1 |
| return count |
|
|