From a846eb1d0a78c1947d8e8439ac16e6087c857451 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 00:17:24 +0100 Subject: [PATCH] fix(settings): save settings under a lock so two saves keep both edits --- app/nullius/migrate.py | 35 ++++-- app/nullius/ondisk.py | 53 ++++++++- app/nullius/settings.py | 168 ++++++++++++++++++---------- app/tests/test_migrate.py | 39 +++++++ app/tests/test_ondisk.py | 110 ++++++++++++++++++ app/tests/test_provider_registry.py | 42 +++++++ app/tests/test_settings.py | 56 +++++++++- docs/concepts.md | 2 +- 8 files changed, 434 insertions(+), 71 deletions(-) diff --git a/app/nullius/migrate.py b/app/nullius/migrate.py index aa59bf934..2ce7c9a08 100644 --- a/app/nullius/migrate.py +++ b/app/nullius/migrate.py @@ -28,6 +28,7 @@ class CopyPlan: directories: set[Path] = field(default_factory=set) catalogue_entries: dict[Path, dict | None] = field(default_factory=dict) catalogue_snapshot: bool = False + settings: Path | None = None # settings.json, when it is written: under its lock def _no_symlinks(path: Path): @@ -122,7 +123,8 @@ def prepare(checkout: Path, licence_source: Path | None = None): workspaces_target = Path(paths.workspaces_dir()).expanduser().resolve() secrets_target = Path(paths.secrets_dir()).expanduser().resolve() _no_symlinks(target) - held = settings.in_file(str(target)) + previous = target.read_bytes() if target.is_file() else None # one snapshot: the merge and apply's check + held = settings.values_of(previous) if previous is not None else {} for name, value in values.items(): if name in held and held[name] != value: raise ValueError(f"Existing setting differs: {name}. Choose a separate NULLIUS_HOME or resolve it first.") @@ -144,11 +146,12 @@ def add(dest, data, mode=0o600): else: pending.files.append((dest, data, mode, None)) - if merged != held or (merged and not target.exists()): + if merged != held or (merged and previous is None): # Merging non-conflicting settings is the one allowed replacement. data = (json.dumps(merged, indent=2, ensure_ascii=False) + "\n").encode() destination(target) - pending.files.append((target, data, 0o600, target.read_bytes() if target.exists() else None)) + pending.files.append((target, data, 0o600, previous)) + pending.settings = target bundled = Path(__file__).resolve().parent / "catalogue" source_catalogue = checkout / "app" / "nullius" / "catalogue" @@ -212,7 +215,8 @@ def add(dest, data, mode=0o600): def apply(pending): - """Write the prepared copy using private files. Original data is untouched.""" + """Write the prepared copy using private files. Original data is untouched. Everything is checked before + anything is written; settings.json is checked again and written under its lock, so a save in between waits.""" for dest, inventory in pending.catalogue_entries.items(): if _inventory(dest) != inventory: raise ValueError(f"Destination changed since preview: {dest}") @@ -229,11 +233,23 @@ def mkdir(parent): for directory in reversed(missing): directory.mkdir(mode=0o700, exist_ok=True) + def write(dest, data, mode, previous): + mkdir(dest.parent) + if dest != pending.settings: + ondisk.write_whole(dest, data, mode=mode) + return + with settings.changing(dest): + if (dest.read_bytes() if dest.exists() else None) != previous: + raise ValueError(f"Destination changed since preview: {dest}") + ondisk.write_whole(dest, data, mode=mode) + + files = sorted(pending.files, key=lambda f: f[0] != pending.settings) # settings first: refused, nothing written + if pending.settings: + write(*files.pop(0)) for directory in sorted(pending.directories): mkdir(directory) - for dest, data, mode, _ in pending.files: - mkdir(dest.parent) - ondisk.write_whole(dest, data, mode=mode) + for dest, data, mode, previous in files: + write(dest, data, mode, previous) def provider_records(values: dict) -> dict: @@ -245,6 +261,9 @@ def provider_records(values: dict) -> dict: old = {f: values.get(f"MODEL_{i}_{part}") for f, part in (("name", "NAME"), ("base", "API_URL"))} if not any(v is not None for v in old.values()): continue + if not settings.is_record(f"MODEL_{i}"): + raise ValueError(f"MODEL_{i} is a setting of its own, not a provider record: " + f"remove {' and '.join(f'MODEL_{i}_{p}' for p in ('NAME', 'API_URL') if f'MODEL_{i}_{p}' in values)} first.") rec = settings.json_object(values.get(f"MODEL_{i}")) or {} rec = {**{f: v for f, v in old.items() if v}, **rec} changes[f"MODEL_{i}"] = json.dumps(rec, ensure_ascii=False) @@ -262,7 +281,7 @@ def migrate_providers(apply_it: bool) -> int: if bad: raise ValueError(" ".join(bad)) if apply_it and changes: - settings.save_many(target, changes) + changes = settings.save_many(target, provider_records) # again, from what the file holds now except (OSError, ValueError) as error: print(f"Migration stopped: {error}", file=sys.stderr) return 1 diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py index f477e2b15..26b15d07b 100644 --- a/app/nullius/ondisk.py +++ b/app/nullius/ondisk.py @@ -6,6 +6,7 @@ import hashlib import os import stat +import time import uuid # a handle that searches a folder without reading it: a folder its writer cannot list (0300) is written all the same @@ -57,16 +58,60 @@ def write_whole(path, data, mode=None) -> None: os.close(folder) +FIRST_WAIT = 1.0 # seconds an opener waits for a lock file made at this moment by another to get its mode + + +def _lock_file(path) -> int: + """*path* open to write, as a lock wants it (NFS locks need a writable descriptor): a regular file, no link + followed, never replaced nor removed. Made when missing, owner read and write whatever the umask; one of + this user's left without owner write (its maker stopped before setting its mode) gets it back, in place; + another refusal is tried again for a moment.""" + until = time.monotonic() + FIRST_WAIT + while True: + try: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + made = True + except FileExistsError: + try: + fd = os.open(path, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except FileNotFoundError: + continue # gone since: made again + except PermissionError: + st = os.lstat(path) + if stat.S_ISREG(st.st_mode) and st.st_uid == os.geteuid() and not st.st_mode & 0o200: + os.chmod(path, stat.S_IMODE(st.st_mode) | 0o200, follow_symlinks=False) + continue + if time.monotonic() >= until: + raise + time.sleep(0.005) + continue + made = False + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + raise OSError(errno.EINVAL, "not a regular file", os.fspath(path)) + if made and stat.S_IMODE(st.st_mode) != 0o600: + os.fchmod(fd, 0o600) # published already: on failure it stays, for the next to repair + except BaseException: + os.close(fd) + raise + return fd + + @contextlib.contextmanager def locked(path): - """One holder of ``path`` at a time, across processes. The file holds nothing.""" + """One holder of ``path`` at a time, across processes and threads. The file holds + nothing and is never a link or a special file.""" import fcntl # POSIX only: imported where the lock is taken - with open(path, "a") as f: - fcntl.flock(f, fcntl.LOCK_EX) + fd = _lock_file(os.fspath(path)) + try: + fcntl.flock(fd, fcntl.LOCK_EX) try: yield finally: - fcntl.flock(f, fcntl.LOCK_UN) + fcntl.flock(fd, fcntl.LOCK_UN) + finally: + os.close(fd) def sha256_of(path) -> str: diff --git a/app/nullius/settings.py b/app/nullius/settings.py index 4d053cca1..c21e4bf7a 100644 --- a/app/nullius/settings.py +++ b/app/nullius/settings.py @@ -22,6 +22,7 @@ """ from __future__ import annotations +import io import os import json import re @@ -268,11 +269,17 @@ def validate(self, value: str) -> Optional[str]: def parse(path: str) -> List[Tuple[str, Optional[str], Optional[str]]]: """The file as a list of (line, key, value): key and value are None for a comment or blank line. Quotes around a value are dropped.""" - out = [] if not os.path.isfile(path): - return out - with open(path, encoding="utf-8") as fh: - if str(path).endswith(".json"): + return [] + with open(path, "rb") as fh: + return _entries(fh.read(), str(path).endswith(".json")) + + +def _entries(data: bytes, as_json: bool) -> List[Tuple[str, Optional[str], Optional[str]]]: + """``parse`` of a file's bytes.""" + out = [] + with io.TextIOWrapper(io.BytesIO(data), encoding="utf-8") as fh: + if as_json: try: values = json.load(fh) except (ValueError, UnicodeError) as e: @@ -457,6 +464,11 @@ def in_file(path: str) -> Dict[str, str]: return {k: v or "" for _, k, v in parse(path) if k} +def values_of(data: bytes) -> Dict[str, str]: + """``in_file`` of settings.json's bytes, read once by the caller.""" + return {k: v or "" for _, k, v in _entries(data, True) if k} + + def agent_key_names(env=None) -> List[str]: """The agent keys' names, as AGENT_KEYS lists them, each once: a name that is not one, or is already something else's (``reserved_agent_keys``), is @@ -531,6 +543,13 @@ def agent_variable(name: str) -> Variable: return Variable(name, GROUPS[2], f"An agent key, {name}: sent to Harbor runs, to the agent that reads it.", "secret") +def changing(path: str): + """One change of the file at a time, the page's and the command's: a lock beside it, owner-only like the file.""" + path = os.fspath(path) + os.makedirs(os.path.dirname(os.path.abspath(path)), mode=0o700, exist_ok=True) + return ondisk.locked(path + ".lock") + + def _write_lines(path: str, lines: List[str]) -> None: """Atomically replace one owner-only settings file; never print values.""" os.makedirs(os.path.dirname(os.path.abspath(path)), mode=0o700, exist_ok=True) @@ -550,16 +569,20 @@ def take(path: str, name: str) -> Optional[str]: setting reads (``unread``).""" if name in BY_NAME or name in STARTUP or name in set(agent_key_names()): raise ValueError(f"{name} is a setting of its own; it is not moved") - value = in_file(path).get(name) - if value is None: - return None - lines = [line for line, key, _ in parse(path) if key != name] - while lines and not lines[-1].strip(): - lines.pop() - _write_lines(path, lines) - if name in LOADED_KEYS: - os.environ.pop(name, None) - LOADED_KEYS.discard(name) + path = os.fspath(path) + if name not in in_file(path): + return None # nothing to take: no lock, nothing created + with changing(path): + value = in_file(path).get(name) + if value is None: + return None + lines = [line for line, key, _ in parse(path) if key != name] + while lines and not lines[-1].strip(): + lines.pop() + _write_lines(path, lines) + if name in LOADED_KEYS: + os.environ.pop(name, None) + LOADED_KEYS.discard(name) return value @@ -619,13 +642,8 @@ def save(path: str, name: str, value: Optional[str]) -> None: save_many(path, {name: value}) -def save_many(path: str, changes: Dict[str, Optional[str]]) -> None: - """Set (or, with None, remove) variables in the file, keeping every - other line as it was, and apply each change to the process environment - unless the environment already held that variable. Every value is - validated before any is written - one bad value and nothing changes; - the file is written whole to a temporary name beside the target, then - renamed.""" +def _valid(changes: Dict[str, Optional[str]]) -> None: + """Every value valid, or ValueError naming each that is not.""" problems = [] listed = changes.get("AGENT_KEYS") if "AGENT_KEYS" in changes else os.environ.get("AGENT_KEYS", "") agents = set() if listed is None or _agent_key_names(listed) else {n.strip() for n in listed.split(",") if n.strip()} @@ -640,42 +658,78 @@ def save_many(path: str, changes: Dict[str, Optional[str]]) -> None: problems.append(f"{name} must be {why}.") if problems: raise ValueError(" ".join(problems)) - # a setting saved under its new name takes its old one out of the file - old = {o for o, n in RENAMED.items() if n in changes and o not in changes} - lines, done = [], set() - for line, key, _ in parse(path): - if key in old: - if key in LOADED_KEYS: - os.environ.pop(key, None) - LOADED_KEYS.discard(key) - continue - if key in changes: - value = changes[key] - if value is not None and key not in done: - lines.append(f"{key}={value}") - done.add(key) # a duplicate line is dropped rather than kept - continue - lines.append(line) - for name, value in changes.items(): - if value is not None and name not in done: - lines.append(f"{name}={value}") - while lines and not lines[-1].strip(): - lines.pop() - _write_lines(path, lines) - for name, value in changes.items(): - if is_record(name) and name in os.environ and name not in LOADED_KEYS: - _merge_env(name, value or "") # a record: the environment's fields stay over the file's - _FROM[name] = os.path.abspath(path) - continue - if name in os.environ and name not in LOADED_KEYS: - continue # the process environment holds it; the file is for the next start - if value is None: - os.environ.pop(name, None) - LOADED_KEYS.discard(name) - else: - os.environ[name] = value - LOADED_KEYS.add(name) - _FROM[name] = os.path.abspath(path) + + +def _not_shadowed(path: str, changes: Dict[str, Optional[str]]) -> None: + """ValueError when a custom provider's old name or URL is set while the file's record of it now holds + that field: the edit would be saved and never read (``providers.record``).""" + old = [(n, m.group(1), "name" if m.group(2) == "NAME" else "base") for n, v in changes.items() + if v is not None and (m := _ENDPOINT_VAR.match(n)) and m.group(2) != "API_KEY" and f"MODEL_{m.group(1)}" not in changes] + if not old: + return + held = in_file(path) + for name, i, field in old: + if field in (json_object(held.get(f"MODEL_{i}")) or {}): + raise ValueError(f"{name} is now part of the provider record MODEL_{i}. Reload, then save again.") + + +def save_many(path: str, changes) -> Dict[str, Optional[str]]: + """Set (or, with None, remove) variables in the file, keeping every + other line as it was, and apply each change to the process environment + unless the environment already held that variable. Every value is + validated before any is written - one bad value and nothing changes; + the file is read, changed and written whole under ``changing``'s lock, + to a temporary name beside the target, then renamed, and the environment + changed before the lock is let go. ``changes`` may be a function of the + file's values, called under the lock, so it changes what is there now. + Returns the changes made.""" + path = os.fspath(path) + if not callable(changes): + _valid(changes) + with changing(path): + if callable(changes): + changes = changes(in_file(path)) + if not changes: + return changes + _valid(changes) + _not_shadowed(path, changes) + # a setting saved under its new name takes its old one out of the file + old = {o for o, n in RENAMED.items() if n in changes and o not in changes} + lines, done = [], set() + for line, key, _ in parse(path): + if key in old: + if key in LOADED_KEYS: + os.environ.pop(key, None) + LOADED_KEYS.discard(key) + continue + if key in changes: + value = changes[key] + if value is not None and key not in done: + lines.append(f"{key}={value}") + done.add(key) # a duplicate line is dropped rather than kept + continue + lines.append(line) + for name, value in changes.items(): + if value is not None and name not in done: + lines.append(f"{name}={value}") + while lines and not lines[-1].strip(): + lines.pop() + _write_lines(path, lines) + for name, value in changes.items(): + if is_record(name) and name in os.environ and name not in LOADED_KEYS: + _merge_env(name, value or "") # a record: the environment's fields stay over the file's + _FROM[name] = os.path.abspath(path) + continue + if name in os.environ and name not in LOADED_KEYS: + continue # the process environment holds it; the file is for the next start + if value is None: + os.environ.pop(name, None) + LOADED_KEYS.discard(name) + else: + os.environ[name] = value + LOADED_KEYS.add(name) + _FROM[name] = os.path.abspath(path) + return changes def example() -> str: diff --git a/app/tests/test_migrate.py b/app/tests/test_migrate.py index a29a3ce84..5c78ad5b1 100644 --- a/app/tests/test_migrate.py +++ b/app/tests/test_migrate.py @@ -56,6 +56,45 @@ def test_preview_then_copy_and_repeat_keep_sources_and_permissions(self): self.assertEqual(self.old.read_bytes(), before) self.assertIn("files_to_write: 0", self.run_cli("--apply")[1]) + def test_a_save_during_apply_is_kept(self): + # a save made between apply's last check and its write waits for it, and is kept + import threading + from nullius import ondisk + dest = Path(paths.settings_file()); dest.parent.mkdir(parents=True) + dest.write_text(json.dumps({"MODEL_API_URL": "https://old.example/v1"})) + pending, _ = migrate.prepare(self.checkout) + real, saves = ondisk.write_whole, [] + + def write(path, data, mode=0o600): + if Path(path) == dest and not saves: + saves.append(threading.Thread(target=settings.save, args=(str(dest), "MODEL_API_URL", "https://new.example/v1"))) + saves[0].start(); saves[0].join(0.5) + real(path, data, mode=mode) + with patch.object(ondisk, "write_whole", write): + migrate.apply(pending) + saves[0].join(5) + held = settings.in_file(str(dest)) + self.assertEqual((held["HOSTS"], held["MODEL_API_URL"]), ("host-alias", "https://new.example/v1")) + + def test_copying_files_holds_no_settings_lock(self): + # the lock covers settings.json alone: a save made while workspace files are copied does not wait + import threading + from nullius import ondisk + workspace = self.checkout / "workspaces/one"; workspace.mkdir(parents=True) + (workspace / "notes.txt").write_text("fixture") + pending, _ = migrate.prepare(self.checkout) + real, saves, dest = ondisk.write_whole, [], Path(paths.settings_file()) + + def write(path, data, mode=0o600): + if Path(path).name == "notes.txt" and not saves: + saves.append(threading.Thread(target=settings.save, args=(str(dest), "MODEL_API_URL", "https://new.example/v1"))) + saves[0].start(); saves[0].join(5) + self.assertFalse(saves[0].is_alive()) + real(path, data, mode=mode) + with patch.object(ondisk, "write_whole", write): + migrate.apply(pending) + self.assertEqual(settings.in_file(str(dest))["MODEL_API_URL"], "https://new.example/v1") + def test_conflict_prevents_all_writes_and_never_prints_values(self): dest = Path(paths.settings_file()); dest.parent.mkdir(parents=True) dest.write_text(json.dumps({"OPENAI_API_KEY": "fixture-existing-secret"})) diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index a1a6ac568..e92f0b8ef 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -218,6 +218,116 @@ def second(): pass + def lock_path(self): + tmp = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, tmp, True) + return tmp, os.path.join(tmp, "thing.lock") + + def test_two_first_holders_under_a_strict_umask_both_get_it(self): + # the second, refused while the first sets the new file's mode, tries again instead of failing + tmp, path = self.lock_path() + old = os.umask(0o277); self.addCleanup(os.umask, old) + real, paused, resume, got = os.fchmod, threading.Event(), threading.Event(), [] + + def fchmod(fd, mode): + if not paused.is_set(): + paused.set(); resume.wait(5) + real(fd, mode) + + def hold(): + with ondisk.locked(path): + got.append(1) + with mock.patch.object(os, "fchmod", fchmod): + one = threading.Thread(target=hold); one.start(); self.assertTrue(paused.wait(5)) + two = threading.Thread(target=hold); two.start(); two.join(0.2) + resume.set(); one.join(5); two.join(5) + self.assertEqual(got, [1, 1]) + self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o600) + with ondisk.locked(path): # and again, the file there + pass + self.assertEqual(os.listdir(tmp), ["thing.lock"]) + + def test_a_write_only_lock_in_a_folder_that_cannot_be_written_is_held(self): + tmp, path = self.lock_path() + open(path, "w").close(); os.chmod(path, 0o200); os.chmod(tmp, 0o500) + self.addCleanup(os.chmod, tmp, 0o700) + with ondisk.locked(path): + pass + + def test_no_hard_link_is_needed(self): + tmp, path = self.lock_path() + with mock.patch.object(os, "link", side_effect=OSError(95, "Operation not supported")): + with ondisk.locked(path): + pass + + def test_a_lock_that_cannot_be_made_holds_no_descriptor(self): + tmp, path = self.lock_path() + old = os.umask(0o277); self.addCleanup(os.umask, old) # a new file that needs its mode set + before = len(os.listdir("/proc/self/fd")) + with mock.patch.object(os, "fchmod", side_effect=PermissionError): + with self.assertRaises(PermissionError): + with ondisk.locked(path): + pass + self.assertEqual(len(os.listdir("/proc/self/fd")), before) + with ondisk.locked(path): # the file left is the lock, held as any other + pass + + def test_a_maker_that_fails_after_another_entered_never_lets_a_third_in(self): + tmp, path = self.lock_path() + old = os.umask(0o277); self.addCleanup(os.umask, old) + paused, resume, inside, leave, order = threading.Event(), threading.Event(), threading.Event(), threading.Event(), [] + + def fchmod(fd, mode): + paused.set(); resume.wait(5) + raise OSError(5, "Input/output error") + + def make(): + with self.assertRaises(OSError): + with ondisk.locked(path): + order.append("A") + + def second(): + with ondisk.locked(path): + inside.set(); leave.wait(5); order.append("B") + + def third(): + with ondisk.locked(path): + order.append("C") + with mock.patch.object(os, "fchmod", fchmod): + a = threading.Thread(target=make); a.start(); self.assertTrue(paused.wait(5)) + b = threading.Thread(target=second); b.start(); self.assertTrue(inside.wait(5)) + resume.set(); a.join(5) + c = threading.Thread(target=third); c.start(); c.join(0.3) + self.assertTrue(c.is_alive()) # B still holds the one lock + leave.set(); b.join(5); c.join(5) + self.assertEqual(order, ["B", "C"]) + + def test_a_lock_left_by_a_maker_killed_before_its_mode_is_used_again(self): + tmp, path = self.lock_path() + app = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(ondisk.__file__)))) + killed = textwrap.dedent(f""" + import os, signal, sys + sys.path.insert(0, {os.path.join(app, "app")!r}) + from nullius import ondisk + os.umask(0o277) + os.fchmod = lambda fd, mode: os.kill(os.getpid(), signal.SIGKILL) + with ondisk.locked({path!r}): + pass + """) + self.assertEqual(subprocess.run([sys.executable, "-c", killed]).returncode, -9) + self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o400) + later = f"import sys; sys.path.insert(0, {os.path.join(app, 'app')!r}); from nullius import ondisk\nwith ondisk.locked({path!r}): pass" + for _ in range(2): + self.assertEqual(subprocess.run([sys.executable, "-c", later], capture_output=True).returncode, 0) + self.assertEqual(os.listdir(tmp), ["thing.lock"]) + + def test_a_linked_lock_is_refused(self): + tmp, path = self.lock_path() + target = os.path.join(tmp, "elsewhere") + open(target, "w").close(); os.symlink(target, path) + with self.assertRaises(OSError): + with ondisk.locked(path): + pass + class Digest(unittest.TestCase): def test_it_is_the_sha256_of_the_bytes(self): with tempfile.NamedTemporaryFile(delete=False) as f: diff --git a/app/tests/test_provider_registry.py b/app/tests/test_provider_registry.py index 0d304e0b3..793f5188b 100644 --- a/app/tests/test_provider_registry.py +++ b/app/tests/test_provider_registry.py @@ -218,6 +218,48 @@ def test_old_names_move_into_records_on_apply_only(self): self.assertFalse({"MODEL_GPU_NAME", "MODEL_GPU_API_URL", "MODEL_NEW_NAME"} & set(after)) self.assertEqual(self.cli()[1].splitlines()[1], "No old provider settings.") + def test_a_url_saved_while_converting_is_read_or_refused(self): + # one save before the conversion's lock, one while it holds it: the effective URL is the last one saved + import threading + self.target.write_text(json.dumps({"MODEL_GPU_NAME": "GPU", "MODEL_GPU_API_URL": "http://gpu-0:8000/v1"})) + real, saves = migrate.provider_records, [] + + def save(url): + try: + settings.save(str(self.target), "MODEL_GPU_API_URL", url); saves.append(url) + except ValueError as e: + saves.append(e) + + def records(values): + t = threading.Thread(target=save, args=(f"http://gpu-{len(saves) + 1}:8000/v1",)); t.start(); t.join(0.5) + threads.append(t) + return real(values) + threads = [] + with patch.object(migrate, "provider_records", records): + self.assertEqual(self.cli("--apply")[0], 0) + for t in threads: + t.join(5) + saved = [s for s in saves if isinstance(s, str)] + self.assertEqual(providers.record("custom:GPU", settings.in_file(str(self.target)))["base"], saved[-1]) + self.assertTrue(all("Reload" in str(e) for e in saves if not isinstance(e, str))) + + def test_a_setting_of_its_own_is_never_made_a_record(self): + before = json.dumps({"MODEL_API_KEY": "sk-gpu-fixture", "MODEL_API_KEY_NAME": ""}) + self.target.write_text(before) + for args in ((), ("--apply",)): + code, said = self.cli(*args) + self.assertEqual(code, 1); self.assertIn("not a provider record", said) + self.assertEqual(self.target.read_text(), before) + + def test_nothing_to_convert_writes_nothing(self): + self.target.parent.rmdir() + self.assertEqual(self.cli("--apply")[0], 0) + self.assertFalse(self.target.parent.exists()) + self.target.parent.mkdir() + self.target.write_text(json.dumps({"MODEL_GPU": json.dumps({"name": "GPU"})})) + self.target.parent.chmod(0o500); self.addCleanup(self.target.parent.chmod, 0o700) + self.assertEqual(self.cli("--apply")[0], 0) + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_settings.py b/app/tests/test_settings.py index 6e64dc3d0..6d2d5493c 100644 --- a/app/tests/test_settings.py +++ b/app/tests/test_settings.py @@ -128,7 +128,61 @@ def test_save_keeps_other_lines_and_applies_live(self): self.assertEqual(text, "# kept\nHOSTS=bench-b\n\nOPENAI_API_KEY=sk-kept-0123456789\nMODEL_API_URL=https://llm.example/v1\n") self.assertEqual(os.environ["HOSTS"], "bench-b"); self.assertEqual(os.environ["MODEL_API_URL"], "https://llm.example/v1") self.assertEqual(stat.S_IMODE(os.stat(self.path).st_mode), 0o600) - self.assertEqual([n for n in os.listdir(self.tmp) if n != ".env"], []) # no temporary file left behind + self.assertEqual([n for n in os.listdir(self.tmp) if n not in (".env", ".env.lock")], []) # no temporary file left behind + + def test_two_saves_at_once_keep_both_edits(self): + # one save paused after it read the file, another saved meanwhile: neither edit is lost + import threading + self.write("HOSTS=bench-a\n") + read, resume, parse, first = threading.Event(), threading.Event(), settings.parse, [] + + def paused(path): + out = parse(path) + if not first: + first.append(1); read.set(); resume.wait(5) + return out + with patch.object(settings, "parse", paused): + one = threading.Thread(target=settings.save, args=(self.path, "HOSTS", "bench-b")) + one.start(); self.assertTrue(read.wait(5)) + two = threading.Thread(target=settings.save, args=(self.path, "MODEL_API_URL", "https://llm.example/v1")) + two.start(); two.join(0.5) + resume.set(); one.join(5); two.join(5) + self.assertEqual(settings.in_file(self.path), {"HOSTS": "bench-b", "MODEL_API_URL": "https://llm.example/v1"}) + + def test_the_saving_process_sees_saves_in_the_order_they_were_written(self): + # one save paused after its write, another saved meanwhile: the environment ends as the file does + import contextlib, threading + from nullius import ondisk + resume, real, first = threading.Event(), ondisk.locked, [] + + @contextlib.contextmanager + def paused(path, *args, **kwargs): + with real(path, *args, **kwargs): + yield + if not first: + first.append(1); resume.wait(5) + with patch.object(ondisk, "locked", paused): + one = threading.Thread(target=settings.save, args=(self.path, "HOSTS", "bench-a")); one.start() + while not first and one.is_alive(): + one.join(0.01) + two = threading.Thread(target=settings.save, args=(self.path, "HOSTS", "bench-b")); two.start(); two.join(0.5) + resume.set(); one.join(5); two.join(5) + self.assertEqual(os.environ["HOSTS"], settings.in_file(self.path)["HOSTS"]) + + def test_saves_keep_working_under_a_strict_umask(self): + old = os.umask(0o277); self.addCleanup(os.umask, old) + settings.save(self.path, "HOSTS", "bench-a") + settings.save(self.path, "HOSTS", "bench-b") + self.assertEqual(settings.in_file(self.path), {"HOSTS": "bench-b"}) + for name in (self.path, self.path + ".lock"): + self.assertEqual(stat.S_IMODE(os.stat(name).st_mode), 0o600) + + def test_a_path_object_saves_and_taking_from_no_file_creates_nothing(self): + settings.save(Path(self.path), "HOSTS", "bench-a") + self.assertEqual(settings.in_file(self.path), {"HOSTS": "bench-a"}) + missing = os.path.join(self.tmp, "none", "settings.json") + self.assertIsNone(settings.take(missing, "SOMETHING_ELSE")) + self.assertFalse(os.path.exists(os.path.dirname(missing))) def test_clear_removes_the_line_and_the_variable(self): self.write("HOSTS=bench-a\nHOSTS=bench-b\nOPENAI_API_KEY=sk-kept-0123456789\n") diff --git a/docs/concepts.md b/docs/concepts.md index 9283e1b20..0d663cb38 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -81,7 +81,7 @@ Several web UIs and commands may use one profile (`NULLIUS_HOME`) at once, withi - Each runs folder (`RUNS_DIR`) is followed by one web UI; a second on the same folder refuses to start. Stopping a run goes through the web UI that follows it. - A job folder has one writer at a time: `standard run`, `standard rerun` or the run itself. -- Leaderboard weights, access tokens, proofs and task flags change under their own lock. Files are replaced whole, never half written. +- Settings, Leaderboard weights, access tokens, proofs and task flags change under their own lock. Files are replaced whole, never half written. Supported: