Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 26 additions & 15 deletions app/nullius/migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from __future__ import annotations

import argparse
import contextlib
from dataclasses import dataclass, field
import json
import os
Expand Down Expand Up @@ -216,14 +217,16 @@ def add(dest, data, mode=0o600):

def apply(pending):
"""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}")
for dest, _, _, previous in pending.files:
_no_symlinks(dest)
if (dest.read_bytes() if dest.exists() else None) != previous:
raise ValueError(f"Destination changed since preview: {dest}")
anything is written; settings.json is checked again and written under its lock, so a save in between waits,
and a benchmark's task sets under theirs (``sets/<benchmark>.lock``)."""
def check():
for dest, inventory in pending.catalogue_entries.items():
if _inventory(dest) != inventory:
raise ValueError(f"Destination changed since preview: {dest}")
for dest, _, _, previous in pending.files:
_no_symlinks(dest)
if (dest.read_bytes() if dest.exists() else None) != previous:
raise ValueError(f"Destination changed since preview: {dest}")

def mkdir(parent):
missing = []
Expand All @@ -243,13 +246,21 @@ def write(dest, data, mode, 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, previous in files:
write(dest, data, mode, previous)
check() # a refusal makes nothing, lock included
locks = sorted({d.with_name(d.name + ".lock") for d in pending.catalogue_entries if d.parent.name == "sets"})
with contextlib.ExitStack() as held:
for lock in locks:
_no_symlinks(lock)
mkdir(lock.parent)
held.enter_context(ondisk.locked(lock))
check()
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, previous in files:
write(dest, data, mode, previous)


def provider_records(values: dict) -> dict:
Expand Down
137 changes: 82 additions & 55 deletions app/nullius/standard/runner/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"""
from __future__ import annotations

import contextlib
import hashlib
import json
import os
Expand Down Expand Up @@ -172,6 +173,16 @@ def _folder(benchmark: Optional[str], root: Optional[str]) -> str:
return _contained(folder, folder)


@contextlib.contextmanager
def _changing(benchmark: str, root: Optional[str]):
"""One change of ``benchmark``'s sets at a time, across processes: its free names are read and written under
``sets/<benchmark>.lock``, made where a change will write (a refusal or a change of nothing comes first)."""
base = os.path.dirname(_folder(benchmark, root))
os.makedirs(base, exist_ok=True)
with ondisk.locked(os.path.join(base, benchmark + ".lock")): # not a key: never read as a folder
yield


def path_of(benchmark: str, name: str, root: Optional[str] = None) -> str:
folder = _folder(benchmark, root)
return _contained(os.path.join(folder, check_name(name) + ".json"), folder)
Expand Down Expand Up @@ -482,19 +493,20 @@ def create(bench: dict, label: str, *, dataset: Optional[str] = None, units: Opt
unknown = set(ids) - {q["id"] for q in available.get(u, [])}
if unknown:
raise Refused(f"unknown or excluded questions of {u}: " + ", ".join(sorted(unknown)))
entry = {"id": uuid.uuid4().hex, "name": name_for(bench["key"], label, root), "label": label,
"description": description or "", "benchmark": bench["key"],
**({"version": version_of(bench)} if version_of(bench) else {}),
**({"datasets": list(given)} if len(given) > 1 else {"dataset": next(iter(given))})}
path = path_of(bench["key"], entry["name"], root)
if os.path.lexists(path):
raise Refused(f"a task set {entry['name']!r} of {bench['key']} exists already ({path})")
listed = given if len(given) > 1 else next(iter(given.values()))
entry["revisions"] = [{"revision": 1, "date": _now(), "note": note or "",
"parts" if len(given) > 1 else "units": listed,
**({"questions": questions} if questions else {}), "hash": _hash_of(entry, listed, questions)}]
write(entry, root)
return entry
with _changing(bench["key"], root):
entry = {"id": uuid.uuid4().hex, "name": name_for(bench["key"], label, root), "label": label,
"description": description or "", "benchmark": bench["key"],
**({"version": version_of(bench)} if version_of(bench) else {}),
**({"datasets": list(given)} if len(given) > 1 else {"dataset": next(iter(given))})}
path = path_of(bench["key"], entry["name"], root)
if os.path.lexists(path):
raise Refused(f"a task set {entry['name']!r} of {bench['key']} exists already ({path})")
listed = given if len(given) > 1 else next(iter(given.values()))
entry["revisions"] = [{"revision": 1, "date": _now(), "note": note or "",
"parts" if len(given) > 1 else "units": listed,
**({"questions": questions} if questions else {}), "hash": _hash_of(entry, listed, questions)}]
write(entry, root)
return entry


def _file_of(benchmark: str, name: str, root: Optional[str]) -> str:
Expand All @@ -510,33 +522,39 @@ def rename(benchmark: str, name: str, label: str, root: Optional[str] = None) ->
"""The entry labelled ``label`` and named by it (``name_for``, its own name free), its id, description and list
kept: written under the new name, then the old file removed. Refused: a label it has already or one not
allowed, and an entry that cannot be read."""
old = _file_of(benchmark, name, root)
entry = load(benchmark, name, root)
label = check_label(label)
if label == label_of(entry):
raise Refused(f"the task set {name} is named {label!r} already")
new = name_for(benchmark, label, root, but=name)
if new != name and os.path.lexists(os.path.join(_folder(benchmark, root), new + ".json")):
raise Refused(f"a task set {new!r} of {benchmark} exists already")
entry = dict(entry, name=new, label=label)
write(entry, root)
if new != name:
os.unlink(old)
return entry
_file_of(benchmark, name, root) # refused before the lock is made: a set not there,
if check_label(label) == label_of(load(benchmark, name, root)): # or its own label
raise Refused(f"the task set {name} is named {label.strip()!r} already")
with _changing(benchmark, root):
old = _file_of(benchmark, name, root)
entry = load(benchmark, name, root)
label = check_label(label)
if label == label_of(entry):
raise Refused(f"the task set {name} is named {label!r} already")
new = name_for(benchmark, label, root, but=name)
if new != name and os.path.lexists(os.path.join(_folder(benchmark, root), new + ".json")):
raise Refused(f"a task set {new!r} of {benchmark} exists already")
entry = dict(entry, name=new, label=label)
write(entry, root)
if new != name:
os.unlink(old)
return entry


def delete(benchmark: str, name: str, root: Optional[str] = None) -> Optional[dict]:
"""Remove the entry's file: the entry as it was, or None when it could not be read (an earlier format, a file
changed by hand). A job that ran it keeps its record."""
path = _file_of(benchmark, name, root)
try:
entry = load(benchmark, name, root)
except NotFound:
raise
except Refused:
entry = None
os.unlink(path)
return entry
_file_of(benchmark, name, root) # a set not there is refused before the lock is made
with _changing(benchmark, root):
path = _file_of(benchmark, name, root)
try:
entry = load(benchmark, name, root)
except NotFound:
raise
except Refused:
entry = None
os.unlink(path)
return entry


def _job_config(job_dir: str) -> dict:
Expand Down Expand Up @@ -680,23 +698,32 @@ def import_path(path: str, root: Optional[str] = None) -> Tuple[dict, bool]:
raise NotFound(f"{path}: no such file or job")
check(incoming, path)
bench, name = incoming["benchmark"], incoming["name"]
others, _ = entries(bench, root)
holder = next((e for e in others if e["id"] == incoming["id"] and e["name"] != name), None)
if holder:
raise Refused(f"the set {incoming['id']} is here already, named {holder['name']}")
target = path_of(bench, name, root)
if not os.path.exists(target):
incoming = {k: v for k, v in incoming.items() if k != "schema"}
write(incoming, root)
return incoming, True
here = load(bench, name, root)
if here["id"] != incoming["id"]:
raise Refused(f"a task set {name!r} of {bench} with another id is here already ({target})")
if datasets_of(here) != datasets_of(incoming):
raise Refused(f"the set {name} here differs in its datasets: {', '.join(datasets_of(here))}, "
f"not {', '.join(datasets_of(incoming))}")
mine, theirs = latest(here), latest(incoming)
if mine["hash"] != theirs["hash"]:
raise Refused(f"the set {name} holds another list here (hash {mine['hash'][:12]}, not {theirs['hash'][:12]}): "
"the same id with another list")
return here, False
def settle(held):
others, _ = entries(bench, root)
holder = next((e for e in others if e["id"] == incoming["id"] and e["name"] != name), None)
if holder:
raise Refused(f"the set {incoming['id']} is here already, named {holder['name']}")
target = path_of(bench, name, root)
if not os.path.exists(target):
if not held: # it will write: again, under the lock
return None, True
entry = {k: v for k, v in incoming.items() if k != "schema"}
write(entry, root)
return entry, True
here = load(bench, name, root)
if here["id"] != incoming["id"]:
raise Refused(f"a task set {name!r} of {bench} with another id is here already ({target})")
if datasets_of(here) != datasets_of(incoming):
raise Refused(f"the set {name} here differs in its datasets: {', '.join(datasets_of(here))}, "
f"not {', '.join(datasets_of(incoming))}")
mine, theirs = latest(here), latest(incoming)
if mine["hash"] != theirs["hash"]:
raise Refused(f"the set {name} holds another list here (hash {mine['hash'][:12]}, not {theirs['hash'][:12]}): "
"the same id with another list")
return here, False

got = settle(False) # a refusal or nothing to write takes no lock
if not got[1]:
return got
with _changing(bench, root):
return settle(True)
83 changes: 82 additions & 1 deletion app/tests/test_migrate.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
"""Explicit migration copies user data without exposing values or changing sources."""
import contextlib
from contextlib import redirect_stdout, redirect_stderr
import io
import json
import os
from pathlib import Path
import shutil
import tempfile
import threading
import unittest
from unittest.mock import patch

from nullius import migrate, paths, settings
from nullius import migrate, ondisk, paths, settings
from nullius.standard.contract import definitions
from nullius.standard.runner import sets

Expand Down Expand Up @@ -122,6 +124,85 @@ def test_workspaces_judgements_and_custom_entries_survive_without_moving_raw_run
self.assertEqual(settings.in_file(paths.settings_file())["RUNS_DIR"], str(self.checkout / "runs"))
self.assertTrue((workspace / "workspace.json").exists())

def test_a_set_made_while_a_migration_publishes_takes_the_next_name(self):
source = self.checkout / "app/nullius/catalogue"
bench = {"key": "fakebench", "datasets": [{"id": "all"}]}
moved = sets.create(bench, "dev", dataset="all", units=["good"], root=str(source))
pending, _ = migrate.prepare(self.checkout)
checked, go, made = threading.Event(), threading.Event(), {}

class Held: # past every check, at its first write
def __getattr__(self, name):
return getattr(ondisk, name)

def write_whole(self, path, *args, **kwargs):
if not checked.is_set():
checked.set()
go.wait(10)
return ondisk.write_whole(path, *args, **kwargs)

def create():
made["set"] = sets.create(bench, "dev", dataset="all", units=["model"])

with patch.object(migrate, "ondisk", Held()):
a = threading.Thread(target=migrate.apply, args=(pending,))
a.start()
self.assertTrue(checked.wait(10))
b = threading.Thread(target=create)
b.start()
b.join(0.5)
go.set()
a.join(10)
b.join(10)
self.assertEqual(sets.load("fakebench", "dev")["id"], moved["id"])
self.assertEqual((made["set"]["name"], sets.revision(sets.load("fakebench", "dev-2"))["units"]), ("dev-2", ["model"]))

def test_a_set_made_while_a_migration_is_refused_is_kept(self):
source = self.checkout / "app/nullius/catalogue"
bench = {"key": "fakebench", "datasets": [{"id": "all"}]}
sets.create(bench, "dev", dataset="all", units=["good"], root=str(source))
pending, _ = migrate.prepare(self.checkout)
locked, go, made = threading.Event(), threading.Event(), {}

class Held: # holding the sets' lock, before its checks under it
def __getattr__(self, name):
return getattr(ondisk, name)

@contextlib.contextmanager
def locked(self, path):
with ondisk.locked(path):
locked.set()
go.wait(10)
yield

def apply():
try:
migrate.apply(pending)
except ValueError as e:
made["refused"] = str(e)

def create():
made["set"] = sets.create(bench, "dev", dataset="all", units=["model"])

with patch.object(migrate, "ondisk", Held()):
a = threading.Thread(target=apply)
a.start()
self.assertTrue(locked.wait(10))
b = threading.Thread(target=create)
b.start()
b.join(0.5)
self.assertTrue(b.is_alive())
changed = Path(paths.settings_file()) # what the preview saw changed: refused
changed.parent.mkdir(parents=True, exist_ok=True)
changed.write_text("{}")
go.set()
a.join(10)
b.join(10)
self.assertIn("changed since preview", made["refused"])
self.assertEqual(made["set"]["name"], "dev")
self.assertEqual(sets.create(bench, "dev", dataset="all", units=["good"])["name"], "dev-2")
self.assertEqual(sets.revision(sets.load("fakebench", "dev"))["units"], ["model"])

def test_task_sets_and_the_lists_of_one_made_before_survive_migration(self):
source = self.checkout / "app/nullius/catalogue"
bench = {"key": "fakebench", "datasets": [{"id": "all"}]}
Expand Down
Loading
Loading