"""Separate Worker inbox/builder. No local-Mac fallback; no inference changes.""" import argparse import json import logging import os import shutil import subprocess import time from logging.handlers import RotatingFileHandler from pathlib import Path from core_client import CoreClient from dataset_store import Store, checksum, read, verify, write from final_snapshot import plan from infrastructure_gaussian_sources import resolve_gaussian_entry HERE = Path(__file__).resolve().parent IMAGE = "sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0" def docker(*args, **kw): return subprocess.run(["docker", *map(str, args)], capture_output=True, check=True, **kw) def source_for(envelope, store, state): bundle = envelope["source"]["bundle_sha256"] for root in (store.root / "sources", state / "infrastructure-sources"): for receipt in sorted(root.glob("*/source.json")): source = read(receipt) if source.get("bundle_sha256") == bundle: if checksum(receipt.parent / source["ply"]) != source["sha256"]: raise ValueError("Cached Gaussian source changed") return receipt.parent, source # Complete conversion is shared across subsequent crops and kept only on # Worker, inside the learning quota. Producer inputs remain read-only. store.capacity(6 * 1024**3) profile = dict( producer_data="D:/NDC_GAUSSIAN_PIPELINE/data", sevenzip="C:/Program Files/7-Zip/7z.exe", splat_transform="tools/splat-transform-3.4.0/node_modules/@playcanvas/splat-transform/bin/cli.mjs", ) entry, native = resolve_gaussian_entry( envelope["source"], envelope["world"], Path(profile["producer_data"]) ) converter = state.parent / profile["splat_transform"] from dataset_store import digest key = digest( dict( bundle=bundle, converter=checksum(converter), adapter="learning-lcc-lod1-native-frame-v1", ) ) root = store.root / "sources" / key root.mkdir(exist_ok=True) ply = root / "full-lod1.ply" partial = root / "building.ply" command = [ shutil.which("node"), "--max-old-space-size=8192", str(converter), "--gpu", "cpu", "--max-workers", "4", "-w", "--select-lod", "1", str(entry), "-r", "180,0,0", str(partial), ] from native_children import NativeChildren children = NativeChildren() with (root / "conversion.log").open("wb") as log: proc = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) try: children.assign(proc) deadline = time.monotonic() + 900 while proc.poll() is None: store.capacity(0) if time.monotonic() > deadline: raise TimeoutError("Gaussian conversion budget exceeded") time.sleep(2) if proc.returncode: raise RuntimeError("Gaussian conversion failed; see bounded source log") finally: if proc.poll() is None: subprocess.run( ["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=30 ) proc.wait(timeout=30) children.close() store.capacity(0) with partial.open("rb") as stream: header = stream.read(65536).split(b"end_header", 1)[0] if not all(name in header for name in (b"opacity", b"scale_0", b"rot_0", b"f_dc_0")): raise ValueError("Conversion lacks Gaussian attributes") os.replace(partial, ply) source = dict( ply=ply.name, sha256=checksum(ply), bundle_sha256=bundle, lod=1, converter_sha256=checksum(converter), native_entrypoint=native["entrypoint"], source_to_world=[[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], gaussian_only=True, collider_input=False, point_cloud_input=False, trajectory_used=False, camera_source="explicit-local-review-window", ) write(root / "source.json", source) return root, source def sync(client, store): for item in client.request("/worker/semantic-edits/pending")["jobs"]: try: key, world = item["revision"], item["world_id"] annotation = client.request( f"/worker/worlds/{world}/semantic-edits/{key}", max_response_bytes=24 * 1024**2 ) envelope = dict( annotation=annotation, world=client.request("/worlds/" + world), source=client.request( "/worker/worlds/" + world + "/infrastructure-source", max_response_bytes=24 * 1024**2, ), renderer_image=IMAGE, ) store.accept(envelope) except Exception: logging.exception("Delivery deferred for revision %s", item["revision"]) acknowledge(client, store) def acknowledge(client, store): # ACK after a durable inbox commit; replay also covers a lost HTTP response. for key, receipt in store.db.execute( "SELECT id,receipt FROM jobs WHERE acknowledged IS NULL " "OR acknowledged != receipt ORDER BY rowid" ).fetchall(): envelope = read(store.root / "inbox" / (key + ".json")) world = envelope["world"]["world_id"] client.request(f"/worker/worlds/{world}/semantic-edits/{key}/receipt", json.loads(receipt)) with store.db: store.db.execute("UPDATE jobs SET acknowledged=? WHERE id=?", (receipt, key)) def occupied(state): return any( (state / name).exists() for name in ( "active.json", "editor-active.json", "route-active.json", "infrastructure-active.json", ) ) def build(key, store, state): container = "ndc-semantic-sample-" + key[:16] # Only our exact owned name, left after a killed host process, is reconciled. prior = subprocess.run( ["docker", "inspect", container, "--format", '{{index .Config.Labels "com.nodedc.role"}}'], capture_output=True, timeout=15, ) if prior.returncode == 0: if prior.stdout.decode().strip() != "semantic-sample": raise ValueError("Container name belongs to another owner") docker("rm", "-f", container, timeout=30) staging = store.root / "work" / key staging.mkdir(exist_ok=True) output = staging / "dataset" output.mkdir(exist_ok=True) envelope = read(store.root / "inbox" / (key + ".json")) if store.accept(envelope) != key: raise ValueError("Stored inbox revision changed") snapshot = plan(envelope["annotation"]["package"]) plan_path = staging / "plan.json" if plan_path.exists() and read(plan_path) != snapshot: raise ValueError("Resumed snapshot identity changed") write(plan_path, snapshot) execution = dict( release=read(HERE / "release.json")["id"], renderer=IMAGE, annotation=envelope["annotation"]["sha256"], ) execution_path = staging / "execution.json" if execution_path.exists() and read(execution_path) != execution: raise ValueError("Resume requires the original builder/image/annotation identity") write(execution_path, execution) source_dir, source = source_for(envelope, store, state) source = dict( source, world_sha256=envelope["world"]["sha256"], collider_sha256=envelope["world"].get("collider_sha256"), ) store.capacity(512 * 1024**2) write(staging / "envelope.json", envelope) write(staging / "source.json", source) kernels = store.root / "cache" / IMAGE.removeprefix("sha256:") kernels.mkdir(parents=True, exist_ok=True) image_env = json.loads( docker("image", "inspect", IMAGE, "--format", "{{json .Config.Env}}", timeout=20).stdout ) inherited = next((e.partition("=")[2] for e in image_env if e.startswith("PYTHONPATH=")), "") cmd = [ "run", "--detach", "--name", container, "--gpus", "all", "--memory", "6g", "--cpus", "4", "--network", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--tmpfs", "/tmp:rw,exec,size=1073741824", "--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=semantic-learning", "--label", "com.nodedc.role=semantic-sample", "--label", "com.nodedc.managed-by=semantic-learning-worker", "--log-driver", "local", "--log-opt", "max-size=2m", "--log-opt", "max-file=2", "-e", "PYTHONPATH=/builder:" + inherited, "-e", "PYTHONDONTWRITEBYTECODE=1", "-e", "XDG_CACHE_HOME=/tmp/cache", "-e", "TORCH_EXTENSIONS_DIR=/kernels", "-v", str(HERE) + ":/builder:ro", "-v", str(kernels) + ":/kernels", "-v", str(source_dir) + ":/input:ro", "-v", str(staging) + ":/job:ro", "-v", str(output) + ":/output", "--entrypoint", "python3", IMAGE, "-B", "/builder/build_samples.py", ] started = time.monotonic() shards = {} for start in range(0, len(snapshot["windows"]), 4): name = f"part-{start // 4:03d}" part = output / name if (part / "dataset.json").exists(): shards[name] = verify(part) continue if part.exists(): shutil.rmtree(part) # Only the unfinished owned shard; complete shards are immutable. if occupied(state): raise InterruptedError("Yielding GPU before next shard") store.capacity(512 * 1024**2) write( staging / "batch.json", dict(name=name, start=start, stop=start + 4, classes=snapshot["classes"]), ) run_shard(cmd, container, store, state) shards[name] = verify(part) write( staging / "progress.json", dict( completed=len(shards), total=(len(snapshot["windows"]) + 3) // 4, seconds=time.monotonic() - started, ), ) write(output / "plan.json", snapshot) (output / "dataset_reader.py").write_bytes((HERE / "dataset_store.py").read_bytes()) files = { p.name: dict(sha256=checksum(p), bytes=p.stat().st_size) for p in (output / "plan.json", output / "dataset_reader.py") } write( output / "dataset.json", dict( schema_version="missioncore.semantic-collection/v1", shards=shards, files=files, training_eligible=False, revision=key, world_sha256=snapshot["world_sha256"], split_group=snapshot["world_sha256"], classes=snapshot["classes"], seconds=time.monotonic() - started, ), ) result = store.publish(key, output) shutil.rmtree(staging) return result def run_shard(cmd, container, store, state): try: docker(*cmd, timeout=30) deadline = time.monotonic() + 600 while True: status = json.loads( docker("inspect", container, "--format", "{{json .State}}", timeout=15).stdout ) if not status["Running"]: if status["ExitCode"]: logs = docker("logs", "--tail", "30", container, timeout=15) log = (logs.stdout + logs.stderr).decode(errors="replace") raise RuntimeError("Renderer failed: " + log[-4000:]) break store.capacity(0) if occupied(state): raise InterruptedError("Yielding GPU to simulation/infrastructure") if time.monotonic() > deadline: raise TimeoutError("Sample rendering budget exceeded") time.sleep(1) finally: subprocess.run(["docker", "rm", "-f", container], capture_output=True, timeout=30) def main(): parser = argparse.ArgumentParser() parser.add_argument("--root", type=Path, required=True) parser.add_argument("--state", type=Path, required=True) parser.add_argument("--token-file", type=Path, required=True) parser.add_argument("--core", default="http://127.0.0.1:18080") parser.add_argument("--once", action="store_true") args = parser.parse_args() if os.name != "nt" or not args.root.is_absolute() or args.root.resolve().is_relative_to(HERE): raise ValueError("Durable learning requires a separate Worker Windows store") store = Store(args.root) import msvcrt lock = (args.root / "worker.lock").open("a+b") lock.seek(0) lock.write(b"0") lock.flush() lock.seek(0) msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) handler = RotatingFileHandler( args.root / "logs/worker.log", maxBytes=2 * 1024**2, backupCount=2, encoding="utf-8" ) logging.basicConfig( level=logging.INFO, handlers=[handler], format="%(asctime)s %(levelname)s %(message)s" ) # A process death does not kill Docker. Reconcile only this store's names # before resuming an unfinished build or acknowledging a published sample. for (key,) in store.db.execute( "SELECT id FROM jobs WHERE acknowledged IS NULL " "OR acknowledged != receipt OR state='building'" ).fetchall(): name = "ndc-semantic-sample-" + key[:16] found = subprocess.run( ["docker", "inspect", name, "--format", '{{index .Config.Labels "com.nodedc.role"}}'], capture_output=True, timeout=15, ) if found.returncode == 0 and found.stdout.decode().strip() == "semantic-sample": docker("rm", "-f", name, timeout=30) client = CoreClient(args.core, args.token_file, "semantic-learning-v1") while True: try: sync(client, store) except Exception: logging.exception("Core delivery/receipt unavailable; durable Worker inbox retained") try: if not occupied(args.state): key = store.next() if key: logging.info("Preparing revision %s", key) started = time.monotonic() try: try: acknowledge(client, store) except Exception: logging.warning( "Progress receipt deferred; preparation stays on Worker" ) result = build(key, store, args.state) logging.info( "Published %s samples=%s seconds=%.3f", key, result["sample_count"], time.monotonic() - started, ) except InterruptedError: # Scheduling yield is not an invalid annotation attempt. with store.db: store.db.execute( "UPDATE jobs SET attempts=attempts-1 WHERE id=?", (key,) ) logging.info("GPU yielded for %s", key) except Exception as exc: logging.exception("Sample failed %s", key) store.update(key, "failed", error=str(exc)[:4096]) except Exception: logging.exception("Worker build cycle unavailable") if args.once: break time.sleep(10) if __name__ == "__main__": main()