upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorbobcatchris <83428450+bobcatchris@users.noreply.github.com>2026-11-22 13:48:31 -0600
committerbobcatchris <83428450+bobcatchris@users.noreply.github.com>2026-11-22 13:48:31 -0600
commitb5c90c2102ae8a06f0a2b01ad1f4e35fe2b8529f (patch)
treea9c29b4b3eb2ccb9ccc2b13c9854c1d226ad9b59
parent162821017ea3c286c8bec860f3ff94f037912061 (diff)
world_build: keep concurrent builds out of one output
Staging cleanup, publication and stale-chunk pruning all work on the shared output directory, so two builds into it could delete each other's staged chunks. Hold an OS file lock keyed by the normalized output path for the whole build; a second build gets a clear error instead of interfering. The lock lives in the system temp directory, so output contents and failure cleanup are unchanged. Credit @lucastayaralvarenga-ui for the finding.
-rw-r--r--tests/test_world_build_output_lock.py87
-rw-r--r--tools/world_build.py73
2 files changed, 160 insertions, 0 deletions
diff --git a/tests/test_world_build_output_lock.py b/tests/test_world_build_output_lock.py
new file mode 100644
index 000000000..b8a150d87
--- /dev/null
+++ b/tests/test_world_build_output_lock.py
@@ -0,0 +1,87 @@
1"""Concurrent-output regression tests for tools/world_build.py (no game data).
2
3A world build stages chunks in the output directory, publishes them one at a time,
4then prunes stale chunks. Two builds on one output must not interleave: the
5second one must fail while the first holds the lock, and the next build must
6work again after the lock is released.
7"""
8from contextlib import contextmanager
9import os
10import subprocess
11import sys
12import tempfile
13import time
14import unittest
15from unittest import mock
16
17HERE = os.path.dirname(os.path.abspath(__file__))
18ROOT = os.path.dirname(HERE)
19TOOLS = os.path.join(ROOT, "tools")
20for path in (TOOLS, HERE):
21 if path not in sys.path:
22 sys.path.insert(0, path)
23
24import test_world_build as twb # noqa: E402
25import world_build as wb # noqa: E402
26
27CHILD_HOLD_LOCK = """
28import sys, time
29sys.path.insert(0, sys.argv[1])
30import world_build as wb
31with wb._exclusive_output(sys.argv[2]):
32 with open(sys.argv[3], 'w', encoding='ascii') as fh:
33 fh.write('ready')
34 time.sleep(30)
35"""
36
37
38class WorldBuildOutputLockTests(unittest.TestCase):
39 def test_second_process_refuses_while_first_holds_output(self):
40 with tempfile.TemporaryDirectory() as tmp:
41 assets = os.path.join(tmp, "assets")
42 out = os.path.join(tmp, "world")
43 ready = os.path.join(tmp, "ready")
44 twb._write_synthetic_assets(assets, origin_overlap=False)
45 proc = subprocess.Popen(
46 [sys.executable, "-I", "-c", CHILD_HOLD_LOCK, TOOLS, out, ready],
47 stdout=subprocess.PIPE,
48 stderr=subprocess.PIPE,
49 text=True,
50 )
51 try:
52 deadline = time.time() + 10
53 while not os.path.isfile(ready):
54 self.assertIsNone(proc.poll(), "lock holder exited before becoming ready")
55 self.assertLess(time.time(), deadline, "lock holder never became ready")
56 time.sleep(0.05)
57 with self.assertRaisesRegex(RuntimeError, "another world_build is using"):
58 wb.build_world(assets, out, textures=False)
59 self.assertFalse(os.path.exists(os.path.join(out, "chunks")))
60 finally:
61 proc.terminate()
62 try:
63 proc.communicate(timeout=5)
64 except subprocess.TimeoutExpired:
65 proc.kill()
66 proc.communicate(timeout=5)
67
68 def test_build_world_holds_the_output_lock_and_releases_it(self):
69 with tempfile.TemporaryDirectory() as tmp:
70 assets = os.path.join(tmp, "assets")
71 out = os.path.join(tmp, "world")
72 twb._write_synthetic_assets(assets, origin_overlap=False)
73 calls = []
74
75 @contextmanager
76 def fake_lock(path):
77 calls.append(path)
78 yield
79
80 with mock.patch.object(wb, "_exclusive_output", fake_lock):
81 wb.build_world(assets, out, textures=False)
82 wb.build_world(assets, out, textures=False)
83 self.assertEqual(calls, [os.path.abspath(out)] * 2)
84
85
86if __name__ == "__main__":
87 unittest.main()
diff --git a/tools/world_build.py b/tools/world_build.py
index 10916e36a..585a134e6 100644
--- a/tools/world_build.py
+++ b/tools/world_build.py
@@ -26,6 +26,9 @@ from __future__ import annotations
26import argparse 26import argparse
27import array 27import array
28from concurrent.futures import ThreadPoolExecutor 28from concurrent.futures import ThreadPoolExecutor
29from contextlib import contextmanager
30import functools
31import hashlib
29import json 32import json
30import math 33import math
31import os 34import os
@@ -34,6 +37,16 @@ import shutil
34import statistics 37import statistics
35import sys 38import sys
36import tempfile 39import tempfile
40
41try:
42 import fcntl
43except ImportError: # Windows
44 fcntl = None
45try:
46 import msvcrt
47except ImportError: # POSIX
48 msvcrt = None
49import tempfile
37import threading 50import threading
38 51
39_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) 52_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -1232,6 +1245,63 @@ def _prune_stale_chunks(chunks_dir: str, keep_filenames: set[str]) -> None:
1232# world.json is committed. 1245# world.json is committed.
1233CHUNK_STAGING_PREFIX = ".chunks-staging-" 1246CHUNK_STAGING_PREFIX = ".chunks-staging-"
1234_STAGING_BACKUP = "previous" 1247_STAGING_BACKUP = "previous"
1248_WORLD_BUILD_LOCK = "leonida-world-build-"
1249
1250
1251@contextmanager
1252def _exclusive_output(out_dir: str):
1253 """Hold one exclusive build lock for ``out_dir``.
1254
1255 Staging cleanup, publication and stale-chunk pruning all work on the shared output
1256 directory, so two builds must not run there at once. A killed process releases the
1257 OS file lock automatically.
1258 """
1259 # Keep the lock outside the output: a failed build must still leave no output directory,
1260 # and a successful one must contain only chunks/ and world.json.
1261 key = hashlib.sha256(
1262 os.path.normcase(os.path.abspath(out_dir)).encode("utf-8", "surrogatepass")
1263 ).hexdigest()[:20]
1264 lock_path = os.path.join(tempfile.gettempdir(), _WORLD_BUILD_LOCK + key)
1265 with open(lock_path, "a+b") as fh:
1266 fd = fh.fileno()
1267 locked = False
1268 try:
1269 if fcntl is not None:
1270 fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
1271 locked = True
1272 elif msvcrt is not None:
1273 if os.fstat(fd).st_size == 0:
1274 fh.write(b"\0")
1275 fh.flush()
1276 fh.seek(0)
1277 msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
1278 locked = True
1279 else:
1280 raise RuntimeError("no file-lock implementation available")
1281 except OSError as exc:
1282 raise RuntimeError(f"another world_build is using {out_dir}") from exc
1283 try:
1284 yield
1285 finally:
1286 if locked:
1287 if fcntl is not None:
1288 fcntl.flock(fd, fcntl.LOCK_UN)
1289 else:
1290 fh.seek(0)
1291 msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
1292
1293
1294def _with_output_lock(fn):
1295 @functools.wraps(fn)
1296 def wrapped(*args, **kwargs):
1297 out_dir = kwargs.get("out_dir")
1298 if out_dir is None and len(args) > 1:
1299 out_dir = args[1]
1300 if out_dir is None:
1301 raise TypeError("build_world requires an out_dir")
1302 with _exclusive_output(os.path.abspath(out_dir)):
1303 return fn(*args, **kwargs)
1304 return wrapped
1235 1305
1236 1306
1237def _holds_unrestored_chunks(staging_dir: str) -> bool: 1307def _holds_unrestored_chunks(staging_dir: str) -> bool:
@@ -1326,6 +1396,7 @@ def _publish_world(
1326 raise 1396 raise
1327 1397
1328 1398
1399@_with_output_lock
1329def build_world( 1400def build_world(
1330 assets_dir: str, 1401 assets_dir: str,
1331 out_dir: str, 1402 out_dir: str,
@@ -1361,6 +1432,8 @@ def build_world(
1361 those renames can see old and new chunks mixed, and a hard kill there leaves them mixed 1432 those renames can see old and new chunks mixed, and a hard kill there leaves them mixed
1362 under the old world.json. A staging directory whose previous/ still holds chunks is kept 1433 under the old world.json. A staging directory whose previous/ still holds chunks is kept
1363 by later builds as a recovery copy; other leftover staging is removed by the next build. 1434 by later builds as a recovery copy; other leftover staging is removed by the next build.
1435 One build at a time may use an output directory: a second build refuses with a clear error
1436 instead of removing the first build's staging.
1364 """ 1437 """
1365 if chunk_size <= 0 or not math.isfinite(chunk_size): 1438 if chunk_size <= 0 or not math.isfinite(chunk_size):
1366 raise ValueError(f"chunk_size must be positive, got {chunk_size!r}") 1439 raise ValueError(f"chunk_size must be positive, got {chunk_size!r}")