From c509fcdcfd9a6d53719811295622f02b1d52b91d Mon Sep 17 00:00:00 2001 From: Tejas Date: Sun, 15 Nov 2026 21:12:30 +0530 Subject: [PATCH 1/5] fix(simple): add atomic os-level file locks to prevent jsonl corruption --- simple/ovl.py | 8 ++++++++ tests/simple/test_ovl.py | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/simple/ovl.py b/simple/ovl.py index 665eb03b..3f654049 100644 --- a/simple/ovl.py +++ b/simple/ovl.py @@ -27,6 +27,10 @@ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") import argparse +try: + import fcntl +except ImportError: + fcntl = None import hashlib import json import math @@ -480,6 +484,8 @@ def boundary(kind, ctl, o): torch.save(model.state_dict(), out / f"{'base' if kind == 'base' else 'conversation'}-model.pt") chain.append(entry) with (out / "chain.jsonl").open("a", encoding="utf-8") as f: + if fcntl: + fcntl.flock(f.fileno(), fcntl.LOCK_EX) f.write(json.dumps(entry, sort_keys=True) + "\n") f.flush() os.fsync(f.fileno()) @@ -672,6 +678,8 @@ def cmd_verify(a): report["checks"].append({"segment": [k, k + 1], "match": verify_segment(a.data, run, chain, k)}) report["result"] = "PASS" if report["checks"] and all(c.get("match", c.get("initialization")) for c in report["checks"]) else "FAIL" with (run / "local-verifications.jsonl").open("a", encoding="utf-8") as f: + if fcntl: + fcntl.flock(f.fileno(), fcntl.LOCK_EX) f.write(json.dumps(report, sort_keys=True) + "\n") print(f"verify {report['result']}: {len(report['checks'])} checks; " f"{sum('segment' in c for c in report['checks'])} of {len(chain) - 1} segments", flush=True) diff --git a/tests/simple/test_ovl.py b/tests/simple/test_ovl.py index fac9e9c4..a9ab07f7 100644 --- a/tests/simple/test_ovl.py +++ b/tests/simple/test_ovl.py @@ -450,5 +450,32 @@ def test_missing_recipe_fails_before_creating_output(self): self.assertFalse(Path(self.args(0).out).exists()) +class FileLockTests(unittest.TestCase): + def test_verify_locked_write_posix_and_windows_fallback(self): + with tempfile.TemporaryDirectory() as tmp: + run = Path(tmp) + chain = fake_chain([("initial", tiny_state(0)), ("final", tiny_state(1))]) + write_chain(run, chain) + (run / "anchor.json").write_text(json.dumps({ + "chain_entries": len(chain), + "chain_head_sha256": link(chain[-1]) + })) + args = argparse.Namespace(run=str(run), anchor=None, no_anchor=False, + no_timestamps=True, data=None, weights=None, + all=False, segment=[], random=0) + ovl.cmd_verify(args) + ver_file = run / "local-verifications.jsonl" + self.assertTrue(ver_file.exists()) + self.assertEqual(len(ver_file.read_text().strip().splitlines()), 1) + + orig_fcntl = ovl.fcntl + try: + ovl.fcntl = None + ovl.cmd_verify(args) + self.assertEqual(len(ver_file.read_text().strip().splitlines()), 2) + finally: + ovl.fcntl = orig_fcntl + + if __name__ == "__main__": unittest.main() From 8ef2ef10d2e0932a4d8534ee08c5ee50b809899e Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 16 Nov 2026 14:05:15 +0530 Subject: [PATCH 2/5] test(simple): assert fcntl.flock is invoked with LOCK_EX in test_verify --- tests/simple/test_ovl.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/simple/test_ovl.py b/tests/simple/test_ovl.py index a9ab07f7..913ccaf5 100644 --- a/tests/simple/test_ovl.py +++ b/tests/simple/test_ovl.py @@ -7,6 +7,7 @@ import sys import tempfile import unittest +from unittest.mock import ANY, patch from pathlib import Path from unittest import mock @@ -463,7 +464,12 @@ def test_verify_locked_write_posix_and_windows_fallback(self): args = argparse.Namespace(run=str(run), anchor=None, no_anchor=False, no_timestamps=True, data=None, weights=None, all=False, segment=[], random=0) - ovl.cmd_verify(args) + if ovl.fcntl: + with patch.object(ovl.fcntl, "flock", wraps=ovl.fcntl.flock) as mock_flock: + ovl.cmd_verify(args) + mock_flock.assert_called_with(ANY, ovl.fcntl.LOCK_EX) + else: + ovl.cmd_verify(args) ver_file = run / "local-verifications.jsonl" self.assertTrue(ver_file.exists()) self.assertEqual(len(ver_file.read_text().strip().splitlines()), 1) From 7dee4fad9e123e5560f130af3e373acf471473ac Mon Sep 17 00:00:00 2001 From: Tejas Date: Wed, 18 Nov 2026 08:50:18 +0530 Subject: [PATCH 3/5] fix(simple): acquire non-blocking exclusive process lock during train --- simple/ovl.py | 106 +++++++++++++++++++++------------------ tests/simple/test_ovl.py | 47 +++++++++-------- 2 files changed, 81 insertions(+), 72 deletions(-) diff --git a/simple/ovl.py b/simple/ovl.py index 3f654049..ebd04fb4 100644 --- a/simple/ovl.py +++ b/simple/ovl.py @@ -449,54 +449,62 @@ def load_checkpoint(run, entry, model): def cmd_train(a): out = Path(a.out) out.mkdir(parents=True, exist_ok=True) - # A crash right after the file was opened can leave it empty: that is a run with no entries yet. - chain_file = out / "chain.jsonl" - chain = read_chain(out) if chain_file.exists() and chain_file.stat().st_size else [] - model, opt = fresh() - start = None - if chain: - if chain[-1]["kind"] == "final": - sys.exit("run already complete") - check_recipe_and_data(chain, a.data) # resuming on other data or another recipe would break the chain - opt = load_checkpoint(out, chain[-1], model) - start = chain[-1]["control"] - print(f"resuming at {start['phase']} epoch {start['epoch']} step {start['phase_step']}", flush=True) - else: - (out / "recipe.json").write_text(json.dumps(RECIPE, sort_keys=True, indent=1), encoding="utf-8") - stamping = [] - - def boundary(kind, ctl, o): - entry = {"index": len(chain), "kind": kind, "control": ctl, "state": state_digest(model, o), - "model": model_digest(model.state_dict()), - "previous": hashlib.sha256(json.dumps(chain[-1], sort_keys=True).encode()).hexdigest() if chain else None, - "time": time.time()} - if kind == "initial": - entry["environment"] = environment() - entry["recipe"] = hashlib.sha256(json.dumps(RECIPE, sort_keys=True).encode()).hexdigest() - entry["data"] = {p: hashlib.sha256((Path(a.data) / p / "stream.json").read_bytes()).hexdigest() - for p in ("wikipedia", "conversation")} - # Every boundary checkpoint is kept: each one is the start of a verifiable segment. - # Checkpoint first, then the chain entry, so a crash between them is harmless. - tmp = out / "ckpt.tmp" - torch.save({"control": ctl, "model": model.state_dict(), "opt": o.state_dict()}, tmp) - os.replace(tmp, out / f"ckpt-{entry['index']:05d}.pt") - if kind in ("base", "final"): - torch.save(model.state_dict(), out / f"{'base' if kind == 'base' else 'conversation'}-model.pt") - chain.append(entry) - with (out / "chain.jsonl").open("a", encoding="utf-8") as f: - if fcntl: - fcntl.flock(f.fileno(), fcntl.LOCK_EX) - f.write(json.dumps(entry, sort_keys=True) + "\n") - f.flush() - os.fsync(f.fileno()) - print(f"boundary {entry['index']} {kind} step {ctl['global_step']} state {entry['state'][:16]}", flush=True) - if TIMESTAMP: - stamping.append(stamp.stamp_async(out, entry)) - - run_phases(a.data, model, opt, boundary, start) - for t in stamping: - t.join(timeout=120) - print("training complete", flush=True) + lock = (out / ".train.lock").open("a+") + if fcntl: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + lock.close() + sys.exit(f"another train is using {out}") + try: + # A crash right after the file was opened can leave it empty: that is a run with no entries yet. + chain_file = out / "chain.jsonl" + chain = read_chain(out) if chain_file.exists() and chain_file.stat().st_size else [] + model, opt = fresh() + start = None + if chain: + if chain[-1]["kind"] == "final": + sys.exit("run already complete") + check_recipe_and_data(chain, a.data) # resuming on other data or another recipe would break the chain + opt = load_checkpoint(out, chain[-1], model) + start = chain[-1]["control"] + print(f"resuming at {start['phase']} epoch {start['epoch']} step {start['phase_step']}", flush=True) + else: + (out / "recipe.json").write_text(json.dumps(RECIPE, sort_keys=True, indent=1), encoding="utf-8") + stamping = [] + + def boundary(kind, ctl, o): + entry = {"index": len(chain), "kind": kind, "control": ctl, "state": state_digest(model, o), + "model": model_digest(model.state_dict()), + "previous": hashlib.sha256(json.dumps(chain[-1], sort_keys=True).encode()).hexdigest() if chain else None, + "time": time.time()} + if kind == "initial": + entry["environment"] = environment() + entry["recipe"] = hashlib.sha256(json.dumps(RECIPE, sort_keys=True).encode()).hexdigest() + entry["data"] = {p: hashlib.sha256((Path(a.data) / p / "stream.json").read_bytes()).hexdigest() + for p in ("wikipedia", "conversation")} + # Every boundary checkpoint is kept: each one is the start of a verifiable segment. + # Checkpoint first, then the chain entry, so a crash between them is harmless. + tmp = out / "ckpt.tmp" + torch.save({"control": ctl, "model": model.state_dict(), "opt": o.state_dict()}, tmp) + os.replace(tmp, out / f"ckpt-{entry['index']:05d}.pt") + if kind in ("base", "final"): + torch.save(model.state_dict(), out / f"{'base' if kind == 'base' else 'conversation'}-model.pt") + chain.append(entry) + with (out / "chain.jsonl").open("a", encoding="utf-8") as f: + f.write(json.dumps(entry, sort_keys=True) + "\n") + f.flush() + os.fsync(f.fileno()) + print(f"boundary {entry['index']} {kind} step {ctl['global_step']} state {entry['state'][:16]}", flush=True) + if TIMESTAMP: + stamping.append(stamp.stamp_async(out, entry)) + + run_phases(a.data, model, opt, boundary, start) + for t in stamping: + t.join(timeout=120) + print("training complete", flush=True) + finally: + lock.close() def cmd_fork(a): @@ -678,8 +686,6 @@ def cmd_verify(a): report["checks"].append({"segment": [k, k + 1], "match": verify_segment(a.data, run, chain, k)}) report["result"] = "PASS" if report["checks"] and all(c.get("match", c.get("initialization")) for c in report["checks"]) else "FAIL" with (run / "local-verifications.jsonl").open("a", encoding="utf-8") as f: - if fcntl: - fcntl.flock(f.fileno(), fcntl.LOCK_EX) f.write(json.dumps(report, sort_keys=True) + "\n") print(f"verify {report['result']}: {len(report['checks'])} checks; " f"{sum('segment' in c for c in report['checks'])} of {len(chain) - 1} segments", flush=True) diff --git a/tests/simple/test_ovl.py b/tests/simple/test_ovl.py index 913ccaf5..1c80b17a 100644 --- a/tests/simple/test_ovl.py +++ b/tests/simple/test_ovl.py @@ -451,34 +451,37 @@ def test_missing_recipe_fails_before_creating_output(self): self.assertFalse(Path(self.args(0).out).exists()) -class FileLockTests(unittest.TestCase): - def test_verify_locked_write_posix_and_windows_fallback(self): +class TrainLockTests(unittest.TestCase): + def test_second_train_exits_when_folder_locked(self): with tempfile.TemporaryDirectory() as tmp: - run = Path(tmp) - chain = fake_chain([("initial", tiny_state(0)), ("final", tiny_state(1))]) - write_chain(run, chain) - (run / "anchor.json").write_text(json.dumps({ - "chain_entries": len(chain), - "chain_head_sha256": link(chain[-1]) - })) - args = argparse.Namespace(run=str(run), anchor=None, no_anchor=False, - no_timestamps=True, data=None, weights=None, - all=False, segment=[], random=0) + out = Path(tmp) / "run" + out.mkdir() + lock_path = out / ".train.lock" + f = lock_path.open("a+") if ovl.fcntl: - with patch.object(ovl.fcntl, "flock", wraps=ovl.fcntl.flock) as mock_flock: - ovl.cmd_verify(args) - mock_flock.assert_called_with(ANY, ovl.fcntl.LOCK_EX) - else: - ovl.cmd_verify(args) - ver_file = run / "local-verifications.jsonl" - self.assertTrue(ver_file.exists()) - self.assertEqual(len(ver_file.read_text().strip().splitlines()), 1) + ovl.fcntl.flock(f.fileno(), ovl.fcntl.LOCK_EX | ovl.fcntl.LOCK_NB) + try: + args = argparse.Namespace(data="fake_data", out=str(out)) + if ovl.fcntl: + with self.assertRaisesRegex(SystemExit, f"another train is using {out}"): + ovl.cmd_train(args) + self.assertFalse((out / "recipe.json").exists()) + self.assertFalse((out / "chain.jsonl").exists()) + finally: + if ovl.fcntl: + ovl.fcntl.flock(f.fileno(), ovl.fcntl.LOCK_UN) + f.close() + def test_train_lock_windows_fallback_creates_lock_file(self): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "run" + args = argparse.Namespace(data="fake_data", out=str(out)) orig_fcntl = ovl.fcntl try: ovl.fcntl = None - ovl.cmd_verify(args) - self.assertEqual(len(ver_file.read_text().strip().splitlines()), 2) + with self.assertRaises(Exception): + ovl.cmd_train(args) + self.assertTrue((out / ".train.lock").exists()) finally: ovl.fcntl = orig_fcntl From 0affa3bcfa32a8286e25896227245c774ffa6b0c Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 19 Nov 2026 15:26:17 +0530 Subject: [PATCH 4/5] test(simple): mock downstream training in windows fallback to assert clean execution --- tests/simple/test_ovl.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/simple/test_ovl.py b/tests/simple/test_ovl.py index 1c80b17a..e7c8f27e 100644 --- a/tests/simple/test_ovl.py +++ b/tests/simple/test_ovl.py @@ -7,7 +7,7 @@ import sys import tempfile import unittest -from unittest.mock import ANY, patch +from unittest.mock import ANY, MagicMock, patch from pathlib import Path from unittest import mock @@ -479,9 +479,11 @@ def test_train_lock_windows_fallback_creates_lock_file(self): orig_fcntl = ovl.fcntl try: ovl.fcntl = None - with self.assertRaises(Exception): + with patch.object(ovl, "run_phases", return_value=None), \ + patch.object(ovl, "fresh", return_value=(MagicMock(), MagicMock())): ovl.cmd_train(args) self.assertTrue((out / ".train.lock").exists()) + self.assertTrue((out / "recipe.json").exists()) finally: ovl.fcntl = orig_fcntl From 02a9fd17df3a4ee34b2b2b9510b695f34ca8705a Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 19 Nov 2026 15:58:32 +0530 Subject: [PATCH 5/5] style(test): remove unused ANY import in test_ovl --- tests/simple/test_ovl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/simple/test_ovl.py b/tests/simple/test_ovl.py index e7c8f27e..db5f933a 100644 --- a/tests/simple/test_ovl.py +++ b/tests/simple/test_ovl.py @@ -7,7 +7,7 @@ import sys import tempfile import unittest -from unittest.mock import ANY, MagicMock, patch +from unittest.mock import MagicMock, patch from pathlib import Path from unittest import mock