Files
NODEDC_MISSION_CORE/simulation/ai-polygon/infrastructure_gaussian_sources.py
DCCONSTRUCTIONS f48411f8fe feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
2026-10-29 09:10:01 +03:00

229 lines
11 KiB
Python

"""Original LCC + native poses adapter; read-only producer, owned derived PLY.
Provider job/ingest receipts bind the input to the selected project. No scan
names, qualification paths, mesh, or point cloud participate in resolution.
"""
import base64
import hashlib
import json
import math
import re
import shutil
import subprocess
import time
from pathlib import Path, PurePosixPath
from local_state import write_json
from infrastructure_sources import checksum
MAX_POSES_BYTES = 16 * 1024**2
def confined(root, name):
rel = PurePosixPath(name.replace("\\", "/"))
if rel.is_absolute() or ".." in rel.parts or ":" in name:
raise ValueError("Invalid original source member")
path = root.joinpath(*rel.parts)
if path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
raise ValueError("Original source escaped producer package")
return path
def trajectory(raw):
if not 0 < len(raw) <= MAX_POSES_BYTES:
raise ValueError("Trajectory exceeds bounded input size")
doc = json.loads(raw)
poses = doc.get("poses")
if not isinstance(poses, list) or not 100 <= len(poses) <= 500000:
raise ValueError("Missing complete native scanning trajectory")
for pose in poses:
xyz = pose.get("T")
if not isinstance(xyz, list) or len(xyz) != 3 or any(
type(v) not in (int, float) or not math.isfinite(v) for v in xyz
):
raise ValueError("Invalid trajectory coordinate")
return doc
def archive_trajectory(producer, source, package, sevenzip, pulse, fallback=None):
archives = package["files"]
if len(archives) != 1:
raise ValueError("Ambiguous original archive")
descriptor = archives[0]
candidates = []
for receipt in (producer / "ingests").glob("*/record.json"):
record = json.loads(receipt.read_text(encoding="utf-8"))
if record.get("document", {}).get("source", {}).get("bundle_sha256") != source["bundle_sha256"]:
continue
upload = record.get("archive_upload_id", "")
if not re.fullmatch(r"[a-zA-Z0-9-]{1,80}", upload):
raise ValueError("Invalid archive identity")
path = producer / "uploads" / upload
if path.is_file() and not path.is_symlink() and path.stat().st_size == descriptor["byte_length"]:
if checksum(path, pulse) == descriptor["sha256"]:
candidates.append(path)
if not candidates:
if fallback is None:
raise ValueError("Verified original archive is unavailable on this Worker")
return fallback(descriptor)
return read_archive_trajectory(sorted(candidates)[0], sevenzip, pulse)
def read_archive_trajectory(archive, sevenzip, pulse):
listing = subprocess.run([str(sevenzip), "l", "-slt", "-ba", "-sccUTF-8", str(archive)],
capture_output=True, timeout=120, check=True).stdout.decode("utf-8-sig")
members = []
for block in re.split(r"\r?\n\r?\n", listing):
fields = dict(line.split(" = ", 1) for line in block.splitlines() if " = " in line)
name = fields.get("Path", "").replace("\\", "/")
if PurePosixPath(name).name.lower() == "poses.json":
confined(Path("/archive"), name)
if fields.get("Folder") == "+" or not 0 < int(fields.get("Size", 0)) <= MAX_POSES_BYTES:
raise ValueError("Invalid archived trajectory")
members.append((name, int(fields["Size"])))
if len(members) != 1:
raise ValueError("Original archive needs one unambiguous poses.json")
name, size = members[0]
pulse()
raw = subprocess.run([str(sevenzip), "e", "-so", "-spd", str(archive), name],
capture_output=True, timeout=120, check=True).stdout
if len(raw) != size:
raise ValueError("Archived trajectory size mismatch")
trajectory(raw)
return raw
def resolve_gaussian_entry(package, world, producer, pulse=lambda: None):
if package["world_sha256"] != world["sha256"]:
raise ValueError("Gaussian world changed after admission")
# Current renderer/frame qualification is LCC native Z-up with the viewer's
# 180-degree X conversion. Reject unsupported calibrations explicitly.
rx, ry, rz = world["local_scene"]["visual_rotation"]
if abs((rx - 180 + 180) % 360 - 180) > 1e-6 or abs(ry) > 1e-6 or abs(rz) > 1e-6:
raise ValueError("Gaussian infrastructure frame is not qualified for this calibration")
job_id = package["provider_job_id"]
if not re.fullmatch(r"gsp-[0-9]{14}-[a-f0-9]{8}", job_id):
raise ValueError("Invalid Gaussian producer identity")
job = producer / "jobs" / job_id
record = json.loads((job / "job.json").read_text(encoding="utf-8"))
source = record["request"]["source"]
if record.get("state") != "ready" or source["bundle_sha256"] != package["bundle_sha256"] or source["format"] != "lcc":
raise ValueError("Original LCC producer identity mismatch")
root = job / "work/source-bundle"
entries = [m for m in source["members"] if m["logical_path"] == source["entrypoint"]]
if len(entries) != 1 or PurePosixPath(source["entrypoint"]).suffix.lower() != ".lcc":
raise ValueError("Original Gaussian entrypoint is not a verified LCC member")
for member in source["members"]:
# Source mesh members may coexist in a producer record; they are never
# opened by Gaussian analysis, hashed as geometry, or mounted as input.
if PurePosixPath(member["logical_path"]).suffix.lower() not in (".lcc", ".bin"):
continue
path = confined(root, member["logical_path"])
if path.stat().st_size != member["byte_length"] or checksum(path, pulse) != member["sha256"]:
raise ValueError("Original Gaussian member changed")
entry = confined(root, source["entrypoint"])
return entry, source
def resolve_native(package, world, producer, sevenzip, pulse=lambda: None, fallback=None):
entry, source = resolve_gaussian_entry(package, world, producer, pulse)
if package["kind"] == "folder":
p = package["trajectory"]
raw = base64.b64decode(p["base64"], validate=True)
if len(raw) != p["byte_length"] or hashlib.sha256(raw).hexdigest() != p["sha256"]:
raise ValueError("Trajectory transport mismatch")
elif package["kind"] == "archive":
raw = archive_trajectory(producer, source, package, sevenzip, pulse, fallback)
else:
raise ValueError("Unsupported original Gaussian source")
trajectory(raw)
return entry, raw, source
def transferred_trajectory(descriptor, world, state, profile, pulse, client):
if client is None:
raise ValueError("Original archive transfer is unavailable")
identity = descriptor["sha256"]
if not re.fullmatch("[a-f0-9]{64}", identity):
raise ValueError("Invalid archive digest")
cache = Path(state) / "infrastructure-trajectories" / identity
cache.mkdir(parents=True, exist_ok=True)
target = cache / "poses.json"
receipt = cache / "source.json"
if receipt.exists():
record = json.loads(receipt.read_text())
if record["archive_sha256"] != identity or checksum(target, pulse) != record["poses_sha256"]:
raise ValueError("Cached native trajectory changed")
raw = target.read_bytes()
trajectory(raw)
return raw
if shutil.disk_usage(cache).free < descriptor["byte_length"] + 10 * 1024**3:
raise RuntimeError("Insufficient space for temporary original-archive transfer")
archive = cache / "original.archive"
try:
client.download_asset("/api/v1/ai-polygon/worker/worlds/" + world["world_id"] +
"/infrastructure-archive", descriptor, archive, pulse=pulse, authenticated=True)
if archive.stat().st_size != descriptor["byte_length"] or checksum(archive, pulse) != identity:
raise ValueError("Original archive transport mismatch")
raw = read_archive_trajectory(archive, Path(profile["sevenzip"]), pulse)
target.write_bytes(raw)
write_json(receipt, dict(archive_sha256=identity, poses_sha256=hashlib.sha256(raw).hexdigest()))
return raw
finally:
archive.unlink(missing_ok=True)
archive.with_suffix(".part").unlink(missing_ok=True)
def prepare_native(package, world, state, profile, pulse, *, client=None, output_root=None):
runtime = Path(state).parent
entry, poses, source = resolve_native(package, world, Path(profile["producer_data"]),
Path(profile["sevenzip"]), pulse,
lambda descriptor: transferred_trajectory(descriptor, world, state, profile, pulse, client))
converter = runtime / profile["splat_transform"]
key = hashlib.sha256(json.dumps(dict(bundle=source["bundle_sha256"],
poses=hashlib.sha256(poses).hexdigest(), lod=1, adapter=checksum(Path(__file__)),
converter=checksum(converter)), sort_keys=True).encode()).hexdigest()
root = (Path(output_root) if output_root is not None else Path(state) / "infrastructure-sources") / key
root.mkdir(parents=True, exist_ok=True)
receipt = root / "source.json"
ply = root / "full-lod1.ply"
if receipt.exists():
previous = json.loads(receipt.read_text())
if checksum(ply, pulse) != previous["sha256"] or (root / "poses.json").read_bytes() != poses:
raise ValueError("Shared Gaussian analysis source changed")
return root, previous
if shutil.disk_usage(root).free < 30 * 1024**3:
raise RuntimeError("Insufficient disk space for complete Gaussian source adaptation")
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(ply)]
with (root / "adapt.log").open("wb") as log:
proc = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 1800
while proc.poll() is None:
pulse()
if time.monotonic() > deadline:
raise TimeoutError("Gaussian source adaptation timed out")
time.sleep(1)
if proc.returncode:
raise RuntimeError("Complete Gaussian source adaptation failed")
finally:
if proc.poll() is None:
# Windows tree termination covers the converter's own workers.
subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=30)
proc.wait(timeout=30)
with ply.open("rb") as stream:
header = stream.read(65536).split(b"end_header", 1)[0]
if not all(key in header for key in [b"opacity", b"scale_0", b"rot_0", b"f_dc_0"]):
raise ValueError("Adapted source lacks Gaussian attributes")
(root / "poses.json").write_bytes(poses)
result = dict(ply=ply.name, sha256=checksum(ply, pulse), lod=1,
source_to_world=[[1,0,0,0],[0,0,-1,0],[0,1,0,0],[0,0,0,1]],
bundle_sha256=source["bundle_sha256"], poses_sha256=hashlib.sha256(poses).hexdigest(),
adapter_key=key, coverage="complete-source-selected-LOD", spatially_cropped=False,
gaussian_only=True, collider_input=False, point_cloud_input=False)
write_json(receipt, result)
return root, result