From c638a59232a72c8c55a3b39b0e2e8eeb8fec1760 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:27:53 +0000 Subject: [PATCH] Write the filesystem state atomically _sync_write truncated the state file in place and then wrote the new content with a single unchecked os.write and no fsync. A crash, a full disk or a short write between the truncate and the write left an empty or partially written file: the queue state was lost or undecodable, and a short write was even reported as success. Write to a temp file in the same directory, fsync it, os.replace() it over the state file, then fsync the directory. On any failure the temp file is removed and the previous state is untouched. Because the data file's inode now changes on every write, writers serialise on a sidecar .lock file instead of on the data file, and reads need no lock. Old and new writers lock different files, so they must not run against the same state file at the same time. --- README.md | 6 +- jqueue/adapters/storage/filesystem.py | 78 ++++++++++++++------- tests/test_storage_filesystem.py | 97 +++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index d00feb3..1f93ab4 100644 --- a/README.md +++ b/README.md @@ -413,8 +413,10 @@ storage = LocalFileSystemStorage("/var/lib/myapp/queue.json") # accepts str or pathlib.Path; parent directories are created automatically ``` -Uses `fcntl.flock` for POSIX exclusive locking. The etag is a SHA-256 hex digest of -the file content. +Uses `fcntl.flock` on a sidecar `.lock` file for POSIX exclusive locking. The +etag is a SHA-256 hex digest of the file content. Writes go to a temporary file that is +fsynced and atomically renamed over the state file, so a crash or full disk never +leaves a truncated state file behind. **POSIX-only** (Linux, macOS). Not safe across machines or on NFS. ### S3Storage diff --git a/jqueue/adapters/storage/filesystem.py b/jqueue/adapters/storage/filesystem.py index a053d38..d9cc1a9 100644 --- a/jqueue/adapters/storage/filesystem.py +++ b/jqueue/adapters/storage/filesystem.py @@ -13,14 +13,24 @@ deterministic, and always changes when content changes — unlike mtime which can be identical across rapid successive writes on fast machines. A file that is absent or empty is treated as non-existent; its etag is None. -The jqueue codec always produces non-empty JSON, so a 0-byte file only occurs -transiently before the first write completes. +The jqueue codec always produces non-empty JSON. CAS semantics ------------- -write(content, if_match) acquires an exclusive flock, re-reads the current -etag while holding the lock, and raises CASConflictError if it differs from -if_match. The write is performed atomically within the same lock scope. +write(content, if_match) acquires an exclusive flock on a sidecar lock file +(``.lock``), re-reads the current etag while holding the lock, and +raises CASConflictError if it differs from if_match. + +Crash safety +------------ +The new content is written to a temporary file in the same directory, +fsynced, and moved over ``path`` with os.replace(); the directory is then +fsynced. A crash or I/O error mid-write therefore leaves either the old or +the new state on disk — never a truncated or partially written file. Readers +never see a partial file either, so read() needs no lock. + +Writers from before this change locked ``path`` itself, not the sidecar +lock file; do not run old and new writers against the same file at once. POSIX-only (Linux, macOS). Not compatible with NFS or distributed filesystems. """ @@ -28,10 +38,12 @@ from __future__ import annotations import asyncio +import contextlib import dataclasses import fcntl import hashlib import os +import tempfile from pathlib import Path from jqueue.domain.errors import CASConflictError @@ -72,37 +84,57 @@ async def write( def _etag(data: bytes) -> str: return hashlib.sha256(data).hexdigest() + @property + def _lock_path(self) -> Path: + return self.path.with_name(self.path.name + ".lock") + def _sync_read(self) -> tuple[bytes, str | None]: - if not self.path.exists(): + try: + content = self.path.read_bytes() + except FileNotFoundError: return b"", None - with open(self.path, "rb") as fh: - fcntl.flock(fh, fcntl.LOCK_SH) - try: - content = fh.read() - finally: - fcntl.flock(fh, fcntl.LOCK_UN) etag: str | None = self._etag(content) if content else None return content, etag def _sync_write(self, content: bytes, if_match: str | None) -> str: - self.path.parent.mkdir(parents=True, exist_ok=True) - fd = os.open(str(self.path), os.O_RDWR | os.O_CREAT, 0o644) + directory = self.path.parent + directory.mkdir(parents=True, exist_ok=True) + lock_fd = os.open(str(self._lock_path), os.O_RDWR | os.O_CREAT, 0o644) try: - fcntl.flock(fd, fcntl.LOCK_EX) - - existing = os.read(fd, os.fstat(fd).st_size) - real_etag: str | None = self._etag(existing) if existing else None + fcntl.flock(lock_fd, fcntl.LOCK_EX) + _, real_etag = self._sync_read() if real_etag != if_match: raise CASConflictError( f"ETag mismatch: expected {if_match!r}, got {real_etag!r}" ) - os.ftruncate(fd, 0) - os.lseek(fd, 0, os.SEEK_SET) - os.write(fd, content) + fd, tmp_name = tempfile.mkstemp( + dir=directory, prefix=f".{self.path.name}.", suffix=".tmp" + ) + try: + with os.fdopen(fd, "wb") as fh: + fh.write(content) + fh.flush() + os.fsync(fh.fileno()) + os.chmod(tmp_name, 0o644) + os.replace(tmp_name, self.path) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp_name) + raise + _fsync_dir(directory) finally: - fcntl.flock(fd, fcntl.LOCK_UN) - os.close(fd) + fcntl.flock(lock_fd, fcntl.LOCK_UN) + os.close(lock_fd) return self._etag(content) + + +def _fsync_dir(directory: Path) -> None: + """Persist a rename by fsyncing its directory.""" + dir_fd = os.open(str(directory), os.O_RDONLY) + try: + os.fsync(dir_fd) + finally: + os.close(dir_fd) diff --git a/tests/test_storage_filesystem.py b/tests/test_storage_filesystem.py index 986fa83..25adb5a 100644 --- a/tests/test_storage_filesystem.py +++ b/tests/test_storage_filesystem.py @@ -1,3 +1,10 @@ +import asyncio +import os +import resource +import signal +import stat +from pathlib import Path + import pytest from jqueue.adapters.storage.filesystem import LocalFileSystemStorage @@ -98,3 +105,93 @@ async def test_path_accepts_string(tmp_path): await storage.write(b"data", if_match=None) content, _ = await storage.read() assert content == b"data" + + +# --------------------------------------------------------------------------- +# Crash safety: a failed write never leaves a partial file +# --------------------------------------------------------------------------- + + +def _leftovers(tmp_path: Path) -> list[str]: + return sorted(p.name for p in tmp_path.iterdir() if p.name.endswith(".tmp")) + + +async def test_short_write_leaves_previous_content_intact(tmp_path): + """Disk-full style failure mid-write must not truncate the state file.""" + path = tmp_path / "state.json" + storage = LocalFileSystemStorage(path) + old = b'{"version": 1, "jobs": []}' + etag = await storage.write(old) + new = b"x" * 4096 + + soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE) + previous = signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + resource.setrlimit(resource.RLIMIT_FSIZE, (1024, hard)) + try: + try: + await storage.write(new, if_match=etag) + except OSError: + pass + finally: + resource.setrlimit(resource.RLIMIT_FSIZE, (soft, hard)) + signal.signal(signal.SIGXFSZ, previous) + + assert path.read_bytes() in (old, new) + assert _leftovers(tmp_path) == [] + + +async def test_failed_fsync_keeps_old_content_and_cleans_up(tmp_path, monkeypatch): + path = tmp_path / "state.json" + storage = LocalFileSystemStorage(path) + etag = await storage.write(b"old") + + def boom(fd): + raise OSError("EIO") + + monkeypatch.setattr(os, "fsync", boom) + with pytest.raises(OSError, match="EIO"): + await storage.write(b"new", if_match=etag) + monkeypatch.undo() + + assert path.read_bytes() == b"old" + assert _leftovers(tmp_path) == [] + content, still = await storage.read() + assert (content, still) == (b"old", etag) + + +async def test_successful_write_leaves_no_temp_files(tmp_path): + path = tmp_path / "state.json" + storage = LocalFileSystemStorage(path) + etag = await storage.write(b"one") + await storage.write(b"two", if_match=etag) + + assert path.read_bytes() == b"two" + assert _leftovers(tmp_path) == [] + assert stat.S_IMODE(path.stat().st_mode) == 0o644 + + +async def test_failed_cas_leaves_no_temp_files(tmp_path): + storage = LocalFileSystemStorage(tmp_path / "state.json") + await storage.write(b"one") + with pytest.raises(CASConflictError): + await storage.write(b"two", if_match="stale") + assert _leftovers(tmp_path) == [] + + +async def test_concurrent_writers_same_etag_exactly_one_wins(tmp_path): + """The sidecar lock still serialises writers: CAS stays exclusive.""" + path = tmp_path / "state.json" + etag = await LocalFileSystemStorage(path).write(b"base") + + async def attempt(i: int) -> bool: + try: + await LocalFileSystemStorage(path).write(f"w{i}".encode(), etag) + except CASConflictError: + return False + return True + + results = await asyncio.gather(*(attempt(i) for i in range(16))) + + assert results.count(True) == 1 + winner = results.index(True) + assert path.read_bytes() == f"w{winner}".encode()