diff options
| author | bobcatchris <83428450+bobcatchris@users.noreply.github.com> | 2026-11-22 13:48:31 -0600 |
|---|---|---|
| committer | bobcatchris <83428450+bobcatchris@users.noreply.github.com> | 2026-11-22 13:48:31 -0600 |
| commit | b5c90c2102ae8a06f0a2b01ad1f4e35fe2b8529f (patch) | |
| tree | a9c29b4b3eb2ccb9ccc2b13c9854c1d226ad9b59 | |
| parent | 162821017ea3c286c8bec860f3ff94f037912061 (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.py | 87 | ||||
| -rw-r--r-- | tools/world_build.py | 73 |
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 | |||
| 3 | A world build stages chunks in the output directory, publishes them one at a time, | ||
| 4 | then prunes stale chunks. Two builds on one output must not interleave: the | ||
| 5 | second one must fail while the first holds the lock, and the next build must | ||
| 6 | work again after the lock is released. | ||
| 7 | """ | ||
| 8 | from contextlib import contextmanager | ||
| 9 | import os | ||
| 10 | import subprocess | ||
| 11 | import sys | ||
| 12 | import tempfile | ||
| 13 | import time | ||
| 14 | import unittest | ||
| 15 | from unittest import mock | ||
| 16 | |||
| 17 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 18 | ROOT = os.path.dirname(HERE) | ||
| 19 | TOOLS = os.path.join(ROOT, "tools") | ||
| 20 | for path in (TOOLS, HERE): | ||
| 21 | if path not in sys.path: | ||
| 22 | sys.path.insert(0, path) | ||
| 23 | |||
| 24 | import test_world_build as twb # noqa: E402 | ||
| 25 | import world_build as wb # noqa: E402 | ||
| 26 | |||
| 27 | CHILD_HOLD_LOCK = """ | ||
| 28 | import sys, time | ||
| 29 | sys.path.insert(0, sys.argv[1]) | ||
| 30 | import world_build as wb | ||
| 31 | with 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 | |||
| 38 | class 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 | |||
| 86 | if __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 | |||
| 26 | import argparse | 26 | import argparse |
| 27 | import array | 27 | import array |
| 28 | from concurrent.futures import ThreadPoolExecutor | 28 | from concurrent.futures import ThreadPoolExecutor |
| 29 | from contextlib import contextmanager | ||
| 30 | import functools | ||
| 31 | import hashlib | ||
| 29 | import json | 32 | import json |
| 30 | import math | 33 | import math |
| 31 | import os | 34 | import os |
| @@ -34,6 +37,16 @@ import shutil | |||
| 34 | import statistics | 37 | import statistics |
| 35 | import sys | 38 | import sys |
| 36 | import tempfile | 39 | import tempfile |
| 40 | |||
| 41 | try: | ||
| 42 | import fcntl | ||
| 43 | except ImportError: # Windows | ||
| 44 | fcntl = None | ||
| 45 | try: | ||
| 46 | import msvcrt | ||
| 47 | except ImportError: # POSIX | ||
| 48 | msvcrt = None | ||
| 49 | import tempfile | ||
| 37 | import threading | 50 | import 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. |
| 1233 | CHUNK_STAGING_PREFIX = ".chunks-staging-" | 1246 | CHUNK_STAGING_PREFIX = ".chunks-staging-" |
| 1234 | _STAGING_BACKUP = "previous" | 1247 | _STAGING_BACKUP = "previous" |
| 1248 | _WORLD_BUILD_LOCK = "leonida-world-build-" | ||
| 1249 | |||
| 1250 | |||
| 1251 | @contextmanager | ||
| 1252 | def _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 | |||
| 1294 | def _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 | ||
| 1237 | def _holds_unrestored_chunks(staging_dir: str) -> bool: | 1307 | def _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 | ||
| 1329 | def build_world( | 1400 | def 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}") |