Skip to content

Official Codebase of 3DCodeVerse

Python

runlock: a real mutex, held outside the directory a --force wipe deletes

gaoypengd5b51373ee98
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.py
index aacefc04..eba901c9 100644
--- a/harness/codeverse/cli/main.py
+++ b/harness/codeverse/cli/main.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import os
import sys
+from contextlib import ExitStack
from pathlib import Path
from typing import Annotated
@@ -34,6 +35,7 @@ from codeverse.cli.tools_cmd import tools
from codeverse.config import get_settings
from codeverse.contracts.common import TRACK_LANGUAGES, Budget, Language, Track
from codeverse.contracts.spec import Constraints, ReferenceImage, RunOptions, Spec
+from codeverse.runlock import RunLocked, exclusive
app = typer.Typer(
name="3dcv",
@@ -250,6 +252,28 @@ def make(
)
except ValueError as e:
raise C.CliError(f"invalid run spec: {e}") from e
+ # THE run mutex, taken BEFORE the workspace is created (or --force wipes one) and
+ # held through the paid reference call and the run itself: everything below mutates
+ # this run directory, and two 3dcv on one slug corrupt each other (runlock.py).
+ stack = ExitStack()
+ try:
+ stack.enter_context(exclusive(C.runs_root(runs_dir) / run_slug,
+ what=f"3dcv make {run_slug}", action="create"))
+ except RunLocked as e:
+ raise C.CliError(str(e), code=2) from None
+ with stack:
+ _make_in_lock(spec, run_slug, runs_dir, force=force, no_run=no_run, reference=reference,
+ reference_views=reference_views, candidates=candidates, rounds=rounds,
+ max_usd=max_usd, texture=texture, dial=dial, settings=settings,
+ backends=backends, track=track, language=language)
+
+
+def _make_in_lock(spec, run_slug: str, runs_dir, *, force: bool, no_run: bool, reference: bool,
+ reference_views: int, candidates, rounds, max_usd, texture, dial, settings,
+ backends, track, language) -> None:
+ """The body of ``make`` that mutates the run directory — always under the run mutex
+ (``runlock.exclusive``), which is why creating, wiping, writing the spec and the paid
+ reference call can no longer race a second ``3dcv make`` on the same slug."""
ws = C.create_workspace(C.runs_root(runs_dir) / run_slug, force=force)
ws.write_json(ws.spec_path, spec)
ws.commit("spec")
@@ -432,6 +456,18 @@ def resume(
reached a terminal state is refused unless ``--force``: re-entering it spends
money and overwrites its final state."""
ws = C.open_workspace(slug, runs_dir)
+ try: # the run mutex, before the spec is rewritten (a budget raise is a mutation)
+ stack = ExitStack()
+ stack.enter_context(exclusive(ws.root, what=f"3dcv resume {ws.root.name}"))
+ except RunLocked as e:
+ raise C.CliError(str(e), code=2) from None
+ with stack:
+ _resume_in_lock(ws, runs_dir, force=force, max_usd=max_usd, max_minutes=max_minutes,
+ rounds=rounds, candidates=candidates)
+
+
+def _resume_in_lock(ws, runs_dir, *, force: bool, max_usd, max_minutes, rounds, candidates) -> None:
+ """The body of ``resume`` that mutates the run — always under the run mutex."""
spec = C.load_spec(ws)
if (
spec.options.profile
diff --git a/harness/codeverse/runlock.py b/harness/codeverse/runlock.py
index 3538967f..daa69e0b 100644
--- a/harness/codeverse/runlock.py
+++ b/harness/codeverse/runlock.py
@@ -9,17 +9,33 @@ Measured 2026-08-25: a lane launched ``3dcv resume tsr_scn_temple_night`` three
after mistaking a surviving process for someone else's, and two of them ran concurrently
against the same workspace for four minutes.
-Deliberately a PID file and not ``fcntl.flock``: the useful message here is *which*
-process holds the run, so a human can look at it or kill that one PID — the lesson from
-the same day's ``pkill -f "3dcv make"``, which killed thirteen unrelated runs because the
-operator had no way to name just theirs. A lock that says "held by pid 2992370, started
-15:56:25" is worth more than one that only says "busy".
+TWO layers, because each does what the other cannot (2026-08-27):
+
+* :func:`exclusive` — an ``fcntl.flock`` on ``<runs>/.locks/<slug>.lock``, i.e. OUTSIDE
+ the directory a ``--force`` run deletes. This is the actual mutex: the PID file below
+ is written after a check, so two processes could both pass it (and a forced wipe took
+ the lock file with it). The kernel releases a flock when the holder dies, so a crash
+ never leaves a run unenterable.
+* the PID file (:func:`run_lock`) — the human-readable holder record, kept because the
+ useful message here is *which* process holds the run, so a human can look at it or kill
+ that one PID: the lesson from the same day's ``pkill -f "3dcv make"``, which killed
+ thirteen unrelated runs because the operator had no way to name just theirs. A lock
+ that says "held by pid 2992370, started 15:56:25" is worth more than one that only says
+ "busy". The same record is written into the flock file, so a refusal can name the
+ holder either way.
+
+``exclusive`` is re-entrant WITHIN one process (flock is per open file description, so a
+second ``open``+``flock`` from the same process would refuse itself): the CLI takes it at
+the mutation boundary — before a workspace is created, wiped or its spec rewritten — and
+the track's own :func:`run_lock` nests inside it.
"""
from __future__ import annotations
+import fcntl
import json
import os
+import threading
import time
from collections.abc import Iterator
from contextlib import contextmanager
@@ -28,6 +44,8 @@ from pathlib import Path
from codeverse.proc import read_json_or_none
LOCK_NAME = "run.lock"
+#: directory (beside the run dirs, never inside one) holding the flock files
+LOCKS_DIR = ".locks"
class RunLocked(RuntimeError):
@@ -94,14 +112,95 @@ def _held_message(run_root: Path | str, held: dict, *, action: str) -> str:
started = time.strftime("%H:%M:%S", time.localtime(held.get("started", 0)))
name = Path(run_root).name
return (
- f"refusing to {action} run {name}: it is being run right now by pid {held['pid']} "
+ f"refusing to {action} run {name}: it is being run right now by pid {held.get('pid', '?')} "
f"(started {started}: {held.get('what') or '3dcv'}). Two processes on one run "
f"corrupt each other's state. Look at it with `3dcv status {name}`, or stop that "
- f"ONE process with `kill {held['pid']}` — never `pkill -f 3dcv`, which kills every "
+ f"ONE process with `kill {held.get('pid', '?')}` — never `pkill -f 3dcv`, which kills every "
f"other run on this machine too."
)
+def flock_path(run_root: Path | str) -> Path:
+ """The flock file for this run: ``<runs>/.locks/<slug>.lock``.
+
+ Beside the run directory, never inside it — ``create_workspace(force=True)``
+ ``rmtree``s the run root, and a lock that gets deleted mid-hold is no lock."""
+ root = Path(run_root).resolve()
+ return root.parent / LOCKS_DIR / f"{root.name}.lock"
+
+
+_HELD: dict[str, list[int]] = {} # flock path -> [fd, recursion depth] held by THIS process
+_HELD_GUARD = threading.Lock()
+
+
+def _record_of(fd: int) -> dict | None:
+ try:
+ os.lseek(fd, 0, os.SEEK_SET)
+ raw = os.read(fd, 4096).decode("utf-8", "replace").strip()
+ rec = json.loads(raw) if raw else None
+ except (OSError, ValueError):
+ return None
+ return rec if isinstance(rec, dict) else None
+
+
+def _write_record(fd: int, rec: dict) -> None:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, os.SEEK_SET)
+ os.write(fd, json.dumps(rec).encode())
+ os.fsync(fd)
+
+
+@contextmanager
+def exclusive(run_root: Path | str, *, what: str = "", action: str = "enter") -> Iterator[None]:
+ """THE mutex for one run: hold it around every mutation of the run directory.
+
+ Raises :class:`RunLocked` naming the holder when another live process has it.
+ Re-entrant within this process (nested :func:`run_lock` is a no-op); released by
+ the kernel if this process dies, so a crash never wedges the run."""
+ path = flock_path(run_root)
+ key = str(path)
+ with _HELD_GUARD:
+ if (entry := _HELD.get(key)) is not None:
+ entry[1] += 1
+ nested = True
+ else:
+ nested = False
+ if nested:
+ try:
+ yield
+ finally:
+ with _HELD_GUARD:
+ if (entry := _HELD.get(key)) is not None:
+ entry[1] -= 1
+ return
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(path, os.O_CREAT | os.O_RDWR, 0o644)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ held = _record_of(fd) or {}
+ os.close(fd)
+ raise RunLocked(_held_message(run_root, held, action=action)) from None
+ except BaseException:
+ os.close(fd)
+ raise
+ _write_record(fd, {"pid": os.getpid(), "started": time.time(), "what": what})
+ with _HELD_GUARD:
+ _HELD[key] = [fd, 1]
+ try:
+ yield
+ finally:
+ with _HELD_GUARD:
+ _HELD.pop(key, None)
+ try:
+ os.ftruncate(fd, 0) # the file stays (unlinking it races a waiter's open)
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ except OSError:
+ pass
+ finally:
+ os.close(fd)
+
+
@contextmanager
def run_lock(run_root: Path | str, *, what: str = "") -> Iterator[None]:
"""Hold the run directory for this process, or raise :class:`RunLocked`.
@@ -113,15 +212,16 @@ def run_lock(run_root: Path | str, *, what: str = "") -> Iterator[None]:
path.parent.mkdir(parents=True, exist_ok=True)
if (held := _holder(path)) is not None:
raise RunLocked(_held_message(run_root, held, action="enter"))
- rec = {"pid": os.getpid(), "started": time.time(), "what": what}
- tmp = path.with_suffix(".lock.tmp")
- tmp.write_text(json.dumps(rec))
- os.replace(tmp, path) # atomic publish; last writer in a race still leaves ONE holder
- try:
- yield
- finally:
+ with exclusive(run_root, what=what): # the real mutex; a no-op when the CLI holds it
+ rec = {"pid": os.getpid(), "started": time.time(), "what": what}
+ tmp = path.with_suffix(".lock.tmp")
+ tmp.write_text(json.dumps(rec))
+ os.replace(tmp, path) # the human-readable holder record `3dcv status` reads
try:
- if (cur := _holder(path)) is not None and cur.get("pid") == os.getpid():
- path.unlink(missing_ok=True)
- except OSError:
- pass
+ yield
+ finally:
+ try:
+ if (cur := _holder(path)) is not None and cur.get("pid") == os.getpid():
+ path.unlink(missing_ok=True)
+ except OSError:
+ pass
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 7d4f967d..1b264e5e 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -78,10 +78,13 @@ codeverse/
agent (typed AgentJob + ApiAgentOptions), skills.py (SkillsUsage/SkillRead on
RoundRecord: what was attached, what was read)
workspace.py run-dir layout + git snapshots ; events.py JSONL event log
- runlock.py ONE writer per run dir — a PID lock that names its holder so a
- human can kill that one run and not every run on the box
- proc.py stdlib-only subprocess + atomic-JSON primitives (run_subprocess w/ group kill +
- preexec_fn, kill_group, tail, write_json_atomic) and the tolerant readers/writer
+ runlock.py ONE writer per run dir: an fcntl.flock on <runs>/.locks/<slug>.lock
+ (outside the dir a --force wipe deletes; released by the kernel if
+ the holder dies) taken at every CLI mutation boundary, plus the PID
+ file that NAMES the holder so a human can kill that one pid
+ proc.py stdlib-only subprocess + atomic-JSON primitives (ManagedProcess owns every
+ child's lifecycle: group kill on ANY exception, bounded pumps, stdin writer;
+ run_subprocess, kill_group, tail, write_json_atomic, scrub_secrets) and the tolerant readers/writer
(read_json_or_none, iter_jsonl_lines, read_jsonl_lenient, append_jsonl_line) —
shared by languages/spatial/cli/cost/flywheel/gallery/bench. RULE: any
stdlib-only file / JSON / JSONL helper lives HERE; grep proc.py before writing a
diff --git a/harness/tests/core/test_runlock.py b/harness/tests/core/test_runlock.py
index fe2aa7a7..09c00863 100644
--- a/harness/tests/core/test_runlock.py
+++ b/harness/tests/core/test_runlock.py
@@ -4,10 +4,22 @@ from __future__ import annotations
import json
import os
+import time
+from pathlib import Path
import pytest
-from codeverse.runlock import RunLocked, _lock_path, run_lock
+from codeverse.runlock import (
+ LOCK_NAME,
+ LOCKS_DIR,
+ RunLocked,
+ _lock_path,
+ exclusive,
+ flock_path,
+ run_lock,
+)
+
+HARNESS_ROOT = Path(__file__).resolve().parents[2]
def test_a_second_process_cannot_enter_a_locked_run(tmp_path):
@@ -97,3 +109,91 @@ def test_force_still_overwrites_a_dead_run(tmp_path):
_lock_path(root).write_text(json.dumps({"pid": 4194303, "started": 0, "what": "3dcv make ghost"}))
create_workspace(root, force=True) # must not raise
assert not (root / "spec.json").exists(), "a dead run's directory is replaced as before"
+
+
+# ------------------------------------------------------- the flock mutex (2026-08-27)
+def _child_script(run_root: Path, ready: Path, go: Path) -> str:
+ """A second PROCESS that takes the run mutex, announces it, and waits to be told to let go."""
+ return (
+ "import sys, time, pathlib\n"
+ f"sys.path.insert(0, {str(HARNESS_ROOT)!r})\n"
+ "from codeverse.runlock import exclusive, RunLocked\n"
+ f"root, ready, go = pathlib.Path({str(run_root)!r}), pathlib.Path({str(ready)!r}), pathlib.Path({str(go)!r})\n"
+ "try:\n"
+ " with exclusive(root, what='child'):\n"
+ " ready.write_text('held')\n"
+ " while not go.exists():\n"
+ " time.sleep(0.02)\n"
+ "except RunLocked as e:\n"
+ " ready.write_text('refused: ' + str(e))\n"
+ )
+
+
+def test_two_processes_cannot_hold_one_run(tmp_path: Path):
+ """The PID file could be passed by BOTH racers (check, then write); the flock cannot."""
+ import subprocess
+ import sys
+
+ run_root = tmp_path / "runs" / "slug"
+ run_root.mkdir(parents=True)
+ ready, go = tmp_path / "ready", tmp_path / "go"
+ child = subprocess.Popen([sys.executable, "-c", _child_script(run_root, ready, go)])
+ try:
+ for _ in range(500): # wait for the child to actually hold it
+ if ready.exists():
+ break
+ time.sleep(0.02)
+ assert ready.read_text() == "held", "child never took the lock"
+ with pytest.raises(RunLocked) as got, exclusive(run_root):
+ pass
+ assert str(child.pid) in str(got.value) # names the holder, so a human can kill THAT pid
+ finally:
+ go.write_text("release")
+ child.wait(timeout=10)
+ with exclusive(run_root): # free once the holder exits
+ pass
+
+
+def test_a_dead_holder_never_wedges_a_run(tmp_path: Path):
+ """The kernel drops a flock when the holder dies — a killed run stays resumable."""
+ import signal
+ import subprocess
+ import sys
+
+ run_root = tmp_path / "runs" / "slug"
+ run_root.mkdir(parents=True)
+ ready, go = tmp_path / "ready", tmp_path / "go"
+ child = subprocess.Popen([sys.executable, "-c", _child_script(run_root, ready, go)])
+ for _ in range(500):
+ if ready.exists():
+ break
+ time.sleep(0.02)
+ assert ready.read_text() == "held"
+ child.send_signal(signal.SIGKILL)
+ child.wait(timeout=10)
+ with exclusive(run_root): # no stale-PID reasoning needed: the kernel already released it
+ pass
+
+
+def test_the_mutex_is_reentrant_in_one_process(tmp_path: Path):
+ """The CLI holds it at the mutation boundary and the track's run_lock nests inside."""
+ run_root = tmp_path / "runs" / "slug"
+ run_root.mkdir(parents=True)
+ with exclusive(run_root, what="outer"):
+ with run_lock(run_root, what="inner"): # would self-refuse without re-entrancy
+ assert (run_root / ".3dcv" / LOCK_NAME).is_file()
+ with exclusive(run_root, what="inner2"):
+ pass
+ with exclusive(run_root): # fully released after the outermost exit
+ pass
+
+
+def test_the_lock_file_lives_outside_the_run_directory(tmp_path: Path):
+ """A --force wipe rmtree's the run root; a lock inside it would be deleted mid-hold."""
+ run_root = tmp_path / "runs" / "slug"
+ run_root.mkdir(parents=True)
+ with exclusive(run_root):
+ lock = flock_path(run_root)
+ assert lock.is_file()
+ assert run_root not in lock.parents
+ assert lock.parent == run_root.parent / LOCKS_DIR
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index 4fc7cfdb..3cebad94 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -29,7 +29,9 @@ def test_make_no_run_creates_valid_workspace(tmp_path: Path):
"--runs-dir", str(runs), "--no-run", "--dim", "width=0.5", "--must", "four legs",
"--rounds", "2", "--max-usd", "1.5", "--generator", "gemini-cli:gemini-3.7-flash"])
assert r.exit_code == 0, r.output
- dirs = [d for d in runs.iterdir() if d.is_dir()]
+ # `.locks/` (runlock.exclusive) lives beside the run dirs on purpose — a lock inside
+ # the directory a --force wipe deletes is no lock
+ dirs = [d for d in runs.iterdir() if d.is_dir() and not d.name.startswith(".")]
assert len(dirs) == 1
ws = dirs[0]
assert ws.name.startswith("a_wooden_dining_chair_") and (ws / "spec.json").is_file() and (ws / ".git").is_dir()