Files
NODEDC_MISSION_CORE/simulation/ai-polygon/infrastructure_pipeline.py
T
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

226 lines
13 KiB
Python

"""Artifact-owned execution of the Gaussian-only infrastructure stage chain.
All modules and mount aliases come from the shipped definition. Original
sources are read-only; generated stage artifacts belong to one analysis key.
"""
import hashlib
import json
import shutil
import time
from pathlib import Path
from infrastructure_containers import run_container
from infrastructure_sources import checksum
from local_state import write_json
MODULE = Path(__file__).resolve().parents[1] / "urban-plan-research"
DEFINITION = MODULE / "pipeline/definition.json"
GPU_STAGES = {"pose_survey", "ortho_render", "ortho_segment", "mv_render", "mv_infer",
"semantic_layers", "render_coverage", "semantic_symbols", "semantic_compact_symbols"}
SEMANTIC_STAGES = {"ortho_semantic_survey", "ortho_segment", "semantic_layers",
"semantic_symbols", "semantic_compact_symbols"}
def validate_stage_outputs(definition):
"""Cross-group evidence has one declared producer and a later consumer."""
import re
groups = definition["groups"]
positions = {g["group"]: i for i, g in enumerate(groups)}
if len(positions) != len(groups):
raise ValueError("Duplicate pipeline group")
reserved = {"input", "candidate", "out", "survey", "ortho", "blind", "base",
"release", "assets", "run", "evidence", "base_survey", "continuity",
"fullplan", "multiview", "models", "cache", "baseline.json"}
reserved.update(str(alias) for alias in definition.get("aliases", {}).values())
owners = set()
for index, group in enumerate(groups):
for stage, mounts in group.get("stage_outputs", {}).items():
if stage not in group["stages"] or not isinstance(mounts, dict):
raise ValueError("Output owner is not an executable stage")
for alias, target in mounts.items():
if (not re.fullmatch(r"[a-z][a-z0-9_-]*", target)
or target not in positions or positions[target] <= index):
raise ValueError("Output must belong to a later declared group")
if not re.fullmatch(r"/[a-z][a-z0-9_-]*", alias) or alias[1:] in reserved:
raise ValueError("Output shadows or escapes an existing runtime mount")
if target in owners:
raise ValueError("Cross-group output has multiple producers")
owners.add(target)
def stage_output_mounts(output, group, stage):
mounts = []
for alias, target in group.get("stage_outputs", {}).get(stage, {}).items():
path = output / target
if path.is_symlink() or not path.resolve().is_relative_to(output.resolve()):
raise ValueError("Pipeline output escapes owned analysis directory")
path.mkdir(parents=True, exist_ok=True)
mounts.append((path, alias, False))
return mounts
def definition_files(module=MODULE):
definition = json.loads((module / "pipeline/definition.json").read_text())
validate_stage_outputs(definition)
result = {"pipeline/definition.json", "pipeline/config-ortho.json", "pipeline/config-mv.json",
"pipeline/worker-profile.json"}
for group in definition["groups"]:
for alias, relative in group["files"].items():
for name in (alias, relative):
if Path(name).is_absolute() or ".." in Path(name).parts or "\\" in name:
raise ValueError("Pipeline source escapes artifact")
path = module / relative
if path.is_symlink() or not path.resolve().is_relative_to(module.resolve()):
raise ValueError("Pipeline source escapes artifact")
result.add(relative)
if not all(stage + ".py" in group["files"] for stage in group["stages"]):
raise ValueError("Pipeline entrypoint missing from bundle")
return definition, sorted(result)
def prepare_layout(root, module=MODULE):
definition, files = definition_files(module)
hashes = {name: checksum(module / name) for name in files}
snapshot = hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest()
target = root / "modules" / snapshot
for group in definition["groups"]:
for alias, relative in group["files"].items():
dest = target / group["group"] / alias
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists():
if checksum(dest) != hashes[relative]:
raise ValueError("Prepared module bytes changed")
else:
shutil.copyfile(module / relative, dest)
if checksum(dest) != hashes[relative]:
raise ValueError("Module changed during preparation")
# Docker cannot create nested mountpoints below the read-only module
# bind. Reserve empty files before mounting the pinned wheel assets.
for wheel in (module / "pipeline/vendor").glob("*.whl"):
slot = target / group["group"] / wheel.name
if slot.exists() and (slot.is_symlink() or slot.stat().st_size):
raise ValueError("Dependency mountpoint changed")
slot.touch(exist_ok=True)
write_json(root / "source-manifest.json", dict(snapshot=snapshot, files=hashes))
return definition, target, snapshot
def output_inventory(folder):
# Cache acceptance never trusts an exit code alone. Include semantic images,
# geometry, map and reports; exclude diagnostic logs and stage receipts.
return {p.relative_to(folder).as_posix(): checksum(p) for p in sorted(folder.rglob("*"))
if p.is_file() and not p.is_symlink() and p.suffix != ".log"
and not p.name.endswith(("-exit.json", "-execution.json"))}
def run_pipeline(package, source, output, marker, profile, runtime, pulse, *, module=MODULE):
definition, modules, snapshot = prepare_layout(output, module)
stages = [(g, stage) for g in definition["groups"] for stage in g["stages"]]
for name in ["base-survey", "ortho/survey", "ortho/evidence", "multiview/mapillary/evidence",
"geometry", "continuity"]:
(output / name).mkdir(parents=True, exist_ok=True)
for config, dest in [("config-ortho.json", "ortho"), ("config-mv.json", "multiview")]:
cfg = json.loads((module / "pipeline" / config).read_text())
cfg["scenes"] = {"scene": dict(source_survey="base-survey", package="input", trajectory="poses.json")}
for model in cfg.get("models", {}).values():
model["directory"] = str(runtime / model["directory"])
write_json(output / dest / "config.json", cfg)
for target in [output / "poses.json", output / "ortho/poses.json"]:
target.write_bytes((package / "poses.json").read_bytes())
write_json(output / "request.json", dict(source=source))
write_json(output / "baseline.json", dict(type="FeatureCollection", features=[]))
dependencies = module / "pipeline/vendor"
previous = None
deadline = time.monotonic() + profile["maximum_seconds"]
for index, (group, stage) in enumerate(stages):
if time.monotonic() > deadline:
raise TimeoutError("Gaussian infrastructure job exceeded its execution budget")
name = group["group"]
out = output / ("geometry" if name == "base" else name)
out.mkdir(exist_ok=True)
if previous:
check = previous / "crosswalk-standard-check.json"
if check.exists():
(out / check.name).write_bytes(check.read_bytes())
write_json(output / "progress.json", dict(phase="survey" if name == "base" else "refining",
completed=index, total=len(stages)))
pulse()
mounts = [(modules/name, "/candidate", True), (package, "/input", True),
(output/"base-survey", "/base_survey", name != "base"),
(output/"ortho", "/ortho", True),
(output/"ortho/survey", "/survey", name != "base"), (out, "/out", False)]
if name == "base":
runname = "ortho" if stage.startswith("ortho_") else "multiview"
evidence = output / ("ortho/evidence" if runname == "ortho" else "multiview/mapillary/evidence")
mounts += [(output, "/blind", False), (output/"continuity", "/continuity", False),
(output/"baseline.json", "/baseline.json", True),
(output/runname, "/run", False), (evidence, "/evidence", False)]
cfg = json.loads((output/"multiview/config.json").read_text())
for key, model in cfg["models"].items():
mounts.append((Path(model["directory"]), "/models/" + key, True))
else:
mounts += [(output/"geometry", "/base", True), (output/"multiview", "/multiview", True)]
if previous:
mounts.append((previous, "/fullplan", True))
for folder, alias in definition["aliases"].items():
if folder != name and (output/folder).exists():
mounts.append((output/folder, "/"+alias, True))
mounts += stage_output_mounts(output, group, stage)
for destination, relative in group.get("input_files", {}).items():
mounts = [m for m in mounts if m[1] != destination]
mounts.append((output / relative, destination, True))
if stage in group.get("self_symbol_stages", []):
mounts = [m for m in mounts if m[1] != "/symbolplan"]
mounts.append((out, "/symbolplan", True))
if group.get("extra_coverage"):
mounts.append((output / group["extra_coverage"], "/out/coverage", True))
for dependency in dependencies.glob("*.whl"):
mounts.append((dependency, "/candidate/"+dependency.name, True))
semantic = stage in SEMANTIC_STAGES
if semantic:
mounts += [(module.parents[1], "/release", True),
(runtime/profile["semantic_model"], "/assets", True)]
env = dict(SCENE="scene", ORTHO_SCENE="scene", MV_MODEL="mapillary",
PYTHONPATH="/candidate:/candidate/mapping:/release/simulation/ai-polygon",
OPENBLAS_NUM_THREADS="3", OMP_NUM_THREADS="3", HF_HUB_OFFLINE="1",
TRANSFORMERS_OFFLINE="1", HF_HOME="/tmp/hf", MPLCONFIGDIR="/tmp/matplotlib",
XDG_CACHE_HOME="/tmp/cache", TORCH_HOME="/tmp/torch")
env.update(group.get("environment", {}))
env["WINDOW_SOURCE"] = "/candidate/linear_window_support.py"
if group.get("extra_coverage"):
env["EXTRA_COVERAGE_ROOT"] = "/out/coverage"
gpu = semantic or stage in GPU_STAGES
volumes = [("ndc-urban-mapping-cache", "/cache")] if stage in {"pose_survey", "ortho_render", "mv_render", "render_coverage"} else []
if volumes:
env["TORCH_EXTENSIONS_DIR"] = "/cache/torch"
entry = "import runpy;" + ("import torch;torch.cuda.set_per_process_memory_fraction(.30);" if gpu and not semantic else "")
if stage == "final_symbol_admission":
entry += "import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];"
if stage == "semantic_compact_symbols" and not json.loads((out/"symbol-patches.json").read_text())["patches"]:
write_json(out/"symbol-semantics.json", dict(records=[],
patch_manifest_sha256=checksum(out/"symbol-patches.json"),
class_labels=["bicycle"], prompts=["bicycle", "bike symbol", "bicycle road marking"],
class_ids=[0,0,0], manual_rois=[], empty_search=True))
continue
entry += "runpy.run_path('/candidate/"+stage+".py',run_name='__main__')"
phase = str(index).zfill(3)+"-"+stage.replace("_", "-")
started = time.monotonic()
run_container(marker, phase, profile["semantic_image" if semantic else "mapper_image"],
mounts, ["-B", "-c", entry], out, pulse,
min(profile["maximum_stage_seconds"], max(1,deadline-time.monotonic())),
gpu=gpu, executable="python3", environment=env, volumes=volumes, readonly=True,
resources=group.get("stage_resources", {}).get(stage))
write_json(out/(stage+"-execution.json"), dict(snapshot=snapshot, stage=stage,
seconds=time.monotonic()-started, exit_code=0, input_source_sha256=source["sha256"],
poses_sha256=source["poses_sha256"], gaussian_only=True))
# Within a group /fullplan stays the prior group's output.
if index+1 == len(stages) or stages[index+1][0]["group"] != name:
if name != "base" and group.get("map_output", True):
if group.get("map_file"):
(out/"full-map.json").write_bytes((out/group["map_file"]).read_bytes())
previous = out
write_json(out/"group-inventory.json", dict(files=output_inventory(out)))
if previous is None or not (previous/"full-map.json").is_file():
raise ValueError("Pipeline did not produce a complete map")
return previous/"full-map.json", snapshot