Datasets:
File size: 5,399 Bytes
e1ced61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | """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:
# Some filesystems (e.g. network mounts) do not support directory fsync.
# The rename is still atomic; we only lose the durability guarantee.
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
# "ab" never truncates; creates the file if absent.
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
|