From df4fc0ec5bf07d26fadef036cfe3fd0df5b17838 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 3 Dec 2026 21:40:51 +0100 Subject: [PATCH] fix(runs): remove a whole-file write's temp file in its folder after a rename --- app/nullius/ondisk.py | 53 +++++++++++++++++++++++---------- app/tests/test_ondisk.py | 63 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 15 deletions(-) diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py index 0b16688b8..f477e2b15 100644 --- a/app/nullius/ondisk.py +++ b/app/nullius/ondisk.py @@ -2,11 +2,15 @@ from __future__ import annotations import contextlib +import errno import hashlib import os import stat import uuid +# a handle that searches a folder without reading it: a folder its writer cannot list (0300) is written all the same +_SEARCH = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0) or os.O_RDONLY + def write_whole(path, data, mode=None) -> None: """``data`` as the whole of ``path``, or ``path`` left as it was: text, bytes, or a @@ -16,22 +20,41 @@ def write_whole(path, data, mode=None) -> None: of two writers at once, each writes a complete file and the last rename wins. ``mode`` holds from the first byte. The folder is the caller's to make.""" path = os.fspath(path) - part = os.path.join(os.path.dirname(path), f".{uuid.uuid4().hex}.part") # the folder as the system resolves it - fd = os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode) + here, name = os.path.dirname(path), f".{uuid.uuid4().hex}.part" + flags, perm = os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else mode + try: # the folder as the system resolves it, held: a failure removes the file there, moved or not + folder = os.open(here or ".", _SEARCH | os.O_DIRECTORY) + except OSError: + folder = None # no handle on it (no descriptor left, say): by its name try: - text = isinstance(data, str) or callable(data) - with (os.fdopen(fd, "w", encoding="utf-8") if text else os.fdopen(fd, "wb")) as f: - if mode is not None and stat.S_IMODE(os.fstat(fd).st_mode) != mode: - os.fchmod(fd, mode) # the umask took bits off - if callable(data): - data(f) - else: - f.write(data) - os.replace(part, path) - except BaseException: - with contextlib.suppress(OSError): - os.unlink(part) - raise + if folder is not None: + try: + fd = os.open(name, flags, perm, dir_fd=folder) + except OSError as e: + if e.errno not in (errno.EMFILE, errno.ENFILE): + raise + held, folder = folder, None # the folder took the last descriptor: by its name + os.close(held) + if folder is None: + fd = os.open(os.path.join(here, name), flags, perm) + part = name if folder is not None else os.path.join(here, name) + try: + text = isinstance(data, str) or callable(data) + with (os.fdopen(fd, "w", encoding="utf-8") if text else os.fdopen(fd, "wb")) as f: + if mode is not None and stat.S_IMODE(os.fstat(fd).st_mode) != mode: + os.fchmod(fd, mode) # the umask took bits off + if callable(data): + data(f) + else: + f.write(data) + os.replace(os.path.join(here, name), path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(part, dir_fd=folder) + raise + finally: + if folder is not None: + os.close(folder) @contextlib.contextmanager diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index 0df9bfbc2..a1a6ac568 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -3,7 +3,10 @@ import os import shutil import stat +import subprocess +import sys import tempfile +import textwrap import threading import unittest from unittest import mock @@ -108,6 +111,66 @@ def test_a_write_that_fails_leaves_the_file_as_it_was_and_nothing_beside_it(self self.assertEqual(f.read(), "kept") self.assertEqual(self.left(), ["file.json"]) + def test_a_write_whose_folder_is_renamed_leaves_nothing_in_it(self): + folder, moved, rename = os.path.join(self.tmp, "c"), os.path.join(self.tmp, "moved"), os.replace + os.mkdir(folder) + def renamed_first(src, dst): + rename(folder, moved) # another process, just before this write's rename + return rename(src, dst) + with mock.patch.object(os, "replace", renamed_first), self.assertRaises(FileNotFoundError): + ondisk.write_whole(os.path.join(folder, "file.json"), "x") + self.assertEqual((self.left(), os.listdir(moved)), (["moved"], [])) + + @unittest.skipIf(os.geteuid() == 0, "root lists any folder") + def test_a_folder_its_writer_cannot_list_is_written_all_the_same(self): + os.chmod(self.tmp, 0o300) # write and search, no read + self.addCleanup(os.chmod, self.tmp, 0o700) + ondisk.write_whole(self.path, "x", mode=0o600) + os.chmod(self.tmp, 0o700) + with open(self.path) as f: + self.assertEqual((f.read(), self.mode(), self.left()), ("x", 0o600, ["file.json"])) + + def test_a_folder_that_cannot_be_held_is_written_by_its_name(self): + real = os.open + def no_folder(name, flags, *rest, **kw): + if flags & os.O_DIRECTORY: + raise OSError(24, "Too many open files") + return real(name, flags, *rest, **kw) + with mock.patch.object(os, "open", no_folder): + ondisk.write_whole(self.path, "x") + with mock.patch.object(os, "replace", side_effect=OSError("no rename")), self.assertRaises(OSError): + ondisk.write_whole(self.path, "lost") + with open(self.path) as f: + self.assertEqual((f.read(), self.left()), ("x", ["file.json"])) + + def test_one_free_descriptor_is_enough(self): + ondisk.write_whole(self.path, "old") + script = textwrap.dedent(""" + import os, resource, sys + from nullius import ondisk + resource.setrlimit(resource.RLIMIT_NOFILE, (64, resource.getrlimit(resource.RLIMIT_NOFILE)[1])) + held = [] + try: + while True: + held.append(os.open(os.devnull, os.O_RDONLY)) + except OSError: + os.close(held.pop()) # exactly one left + ondisk.write_whole(sys.argv[1], "new") + """) + app = os.path.dirname(os.path.dirname(os.path.abspath(ondisk.__file__))) + subprocess.run([sys.executable, "-c", script, self.path], check=True, env={**os.environ, "PYTHONPATH": app}) + with open(self.path) as f: + self.assertEqual((f.read(), self.left()), ("new", ["file.json"])) + + @unittest.skipUnless(os.path.isdir("/proc/self/fd"), "descriptors counted from /proc") + def test_a_name_that_fails_holds_no_descriptor(self): + before = len(os.listdir("/proc/self/fd")) + with mock.patch.object(ondisk.uuid, "uuid4", side_effect=OSError("no name")): + for _ in range(4): + with self.assertRaises(OSError): + ondisk.write_whole(self.path, "x") + self.assertEqual((len(os.listdir("/proc/self/fd")), self.left()), (before, [])) + def test_writers_of_one_file_at_once_each_finish_and_one_of_them_wins(self): texts = [str(i) * 4096 for i in range(16)] gate, rename, failed = threading.Barrier(len(texts), timeout=5), os.replace, []