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.
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
# Infrastructure queue and operator progress
|
||||
|
||||
The Core owns a persistent FIFO of whole-scene analysis requests; the connected
|
||||
Worker executes one request while holding the existing simulation GPU reservation.
|
||||
Editor preparation, route preparation and simulation retain their existing
|
||||
reservation policy. FIFO here applies to infrastructure analysis requests.
|
||||
|
||||
## Admission and identity
|
||||
|
||||
`InfrastructureJobs.request` binds the Gaussian world hash, collider, local-scene
|
||||
transform and exact provider closure. Repeated requests for an active world return
|
||||
the same job. An explicit recalculation supplies a 32-character lowercase hex
|
||||
request ID and creates an immutable generation. Repeating that ID is idempotent.
|
||||
Retries after failure or cancellation get a new generation. Ready map history is
|
||||
retained; only a validated successful publication replaces the latest map.
|
||||
|
||||
At most 32 queued/running/unreleased jobs are admitted. Overflow is explicit,
|
||||
never eviction. Monotonic persisted sequence numbers determine FIFO independently
|
||||
of directory order or wall-clock precision. Terminal rows still owning resources
|
||||
precede queued rows until cleanup releases them.
|
||||
|
||||
## Dispatch and termination
|
||||
|
||||
Selection, simulation reservation and claim execute under the same job-store lock
|
||||
as cancellation. A queued cancellation therefore cannot strand a reservation
|
||||
between selection and claim. A running cancellation is a request, not a release.
|
||||
The next Worker progress call is rejected, causing the existing stage runner's
|
||||
`finally` to stop/remove its exact owned container. Worker reconciliation then
|
||||
sends the authenticated release receipt. Errors and bounded stage timeouts follow
|
||||
the same cleanup path. Late publication after cancellation is rejected before any
|
||||
map write. Queue state survives Core restart; the Worker's persisted container
|
||||
marker supports reconciliation after Worker restart. A missing Worker or unknown
|
||||
cleanup state keeps the resource reserved; absence of telemetry is not proof that
|
||||
a container stopped.
|
||||
|
||||
## Operator API
|
||||
|
||||
- `GET /api/v1/ai-polygon/infrastructure-analysis/queue`: active jobs and position.
|
||||
- `GET /api/v1/ai-polygon/worlds/{world_id}/infrastructure-analysis`: current job.
|
||||
- `POST` to that world endpoint: `{force, request_id}` (body optional for first run).
|
||||
- `POST .../infrastructure-analysis/{key}/cancel`: world-bound cancellation.
|
||||
|
||||
Progress counts actual completed stages. The 90-stage all-class definition uses 87 historical stage durations, one
|
||||
qualified shared-semantic measurement (251.484 seconds on Smolensk 6.3), and
|
||||
two explicitly estimated missing stages. The old surface/layer pair is replaced
|
||||
by one shared stage; its two former weights are not counted again. A completed-prefix speed ratio adjusts the remaining estimate. Queue wait
|
||||
and source preparation are excluded and labeled as such. A stale heartbeat (>20s)
|
||||
suppresses ETA; elapsed time never synthesizes completion percentage.
|
||||
|
||||
## Acceptance
|
||||
|
||||
The focused backend tests cover 20-job FIFO, duplicate clicks, capacity, stale
|
||||
provider, ownership, cancellation/late-publication barriers, restart, dispatch
|
||||
races and measured progress. The frontend tests exercise 20 immediate clicks,
|
||||
late polling, cancellation/unmount and idempotent retry after an unknown response.
|
||||
`evaluation/queue_worker_canary.py` runs an isolated durable store on Worker006
|
||||
with real bounded Docker containers: exit 7, running cancellation, timeout,
|
||||
waiting cancellation and reopened persistence. It uses the exact Core atomic JSON
|
||||
writer extracted from its frozen source to avoid importing the unrelated Gaussian
|
||||
reader into the native Windows coordinator. No operator maps or jobs are modified.
|
||||
|
||||
## Control-plane disconnection
|
||||
|
||||
Infrastructure computation is owned by Worker. Lost TCP responses and HTTP 5xx
|
||||
responses during progress reporting retain the same running container and local
|
||||
stage chain. Pulses coalesce to the latest local progress; they never create
|
||||
a backlog or replay dispatch. On the explicit expired-session response, Worker
|
||||
registers the same instance and immutable capabilities, then retries the rejected
|
||||
observation. Cancellation, ownership changes and invalid payloads remain terminal.
|
||||
A missing heartbeat does not release the persistent exclusive GPU reservation.
|
||||
|
||||
After local validation produces `urban-map.json`, Worker records its SHA-256 in
|
||||
`infrastructure-active.json` before sending `complete`. Reconciliation delivers
|
||||
this immutable pending result before releasing ownership or polling another job.
|
||||
A lost success response is safe because Core accepts an identical completed map
|
||||
idempotently and rejects changed content. Retry cadence remains bounded when
|
||||
registration works but receipt delivery does not. A confirmed cancellation or
|
||||
publication rejection preserves the local evidence and releases after cleanup.
|
||||
|
||||
This guarantees continuity across Core/tunnel outages while the Worker process
|
||||
and Docker remain alive. It does not claim mid-stage recovery after a Worker/host
|
||||
crash: the existing orphan-container cleanup still applies. Previously failed
|
||||
jobs are immutable history and are not silently reclassified as completed.
|
||||
|
||||
Acceptance includes reconstruction of the actual Core router and persistent GPU
|
||||
queue, plus an isolated Worker canary with real Docker execution, TCP outages,
|
||||
lost completion acknowledgement, cancellation and FIFO advancement.
|
||||
@@ -5,6 +5,8 @@ import ast
|
||||
import hashlib
|
||||
import json
|
||||
import tarfile
|
||||
import runpy
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
@@ -14,10 +16,30 @@ args = parser.parse_args()
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
files = sorted(
|
||||
p
|
||||
for folder in (root / "src", root / "simulation/ai-polygon")
|
||||
for folder in (root / "src", root / "simulation/ai-polygon", root / "simulation/urban-mapping")
|
||||
for p in folder.rglob("*")
|
||||
if p.is_file() and not p.is_symlink() and "__pycache__" not in p.parts
|
||||
if p.is_file() and not p.is_symlink() and "__pycache__" not in p.parts and ".build" not in p.parts
|
||||
)
|
||||
# Only the declared Gaussian pipeline closure ships; historical review scripts
|
||||
# and private qualification directories are not part of the worker artifact.
|
||||
from infrastructure_pipeline import definition_files
|
||||
module = root / "simulation/urban-plan-research"
|
||||
_, urban_files = definition_files(module)
|
||||
files.extend(module / relative for relative in urban_files)
|
||||
# Pinned runtime wheels are artifact assets, never a global pip installation.
|
||||
pins = runpy.run_path(str(module / "catalog_pass/catalog_dependency_pins.py"))["PINS"]
|
||||
cache = args.output / "urban-dependencies"
|
||||
cache.mkdir(exist_ok=True)
|
||||
assets = {}
|
||||
for pin in pins:
|
||||
path = cache / pin["file"]
|
||||
if not path.exists() or hashlib.sha256(path.read_bytes()).hexdigest() != pin["sha256"]:
|
||||
with urllib.request.urlopen(pin["url"], timeout=120) as response:
|
||||
raw = response.read(32 * 1024**2 + 1)
|
||||
if len(raw) > 32 * 1024**2 or hashlib.sha256(raw).hexdigest() != pin["sha256"]:
|
||||
raise ValueError("Pinned urban runtime dependency changed")
|
||||
path.write_bytes(raw)
|
||||
assets["simulation/urban-plan-research/pipeline/vendor/" + pin["file"]] = path
|
||||
files.extend((root / "apps/control-station/public/vendor/playcanvas/draco/1.5.7").glob("*"))
|
||||
# The canonical Rover 006 asset is shared with PlayCanvas, not a second model.
|
||||
for profile in (root / "simulation/ai-polygon/robots").glob("*.json"):
|
||||
@@ -32,12 +54,15 @@ for source in files:
|
||||
manifest = {
|
||||
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
|
||||
}
|
||||
manifest.update({name: hashlib.sha256(p.read_bytes()).hexdigest() for name, p in assets.items()})
|
||||
encoded = json.dumps(manifest, sort_keys=True, indent=2).encode()
|
||||
identity = hashlib.sha256(encoded).hexdigest()
|
||||
path = args.output / ("ai-polygon-" + identity[:16] + ".tgz")
|
||||
with tarfile.open(path, "w:gz") as archive:
|
||||
for p in files:
|
||||
archive.add(p, arcname=p.relative_to(root).as_posix(), recursive=False)
|
||||
for name, asset in assets.items():
|
||||
archive.add(asset, arcname=name, recursive=False)
|
||||
manifest_path = path.with_suffix(".manifest.json")
|
||||
manifest_path.write_bytes(encoded)
|
||||
print(
|
||||
|
||||
@@ -40,7 +40,9 @@ class CoreClient:
|
||||
self.instance = instance
|
||||
self._connections = threading.local()
|
||||
|
||||
def request(self, path: str, body=None):
|
||||
def request(self, path: str, body=None, *, max_response_bytes=4 * 1024**2):
|
||||
if not 0 < max_response_bytes <= 24 * 1024**2:
|
||||
raise ValueError("Core response budget exceeds bounded transport")
|
||||
connection = getattr(self._connections, "connection", None)
|
||||
if (
|
||||
connection is not None
|
||||
@@ -63,8 +65,8 @@ class CoreClient:
|
||||
},
|
||||
)
|
||||
response = connection.getresponse()
|
||||
raw = response.read(4 * 1024**2 + 1)
|
||||
if len(raw) > 4 * 1024**2:
|
||||
raw = response.read(max_response_bytes + 1)
|
||||
if len(raw) > max_response_bytes:
|
||||
raise RuntimeError("Core response exceeds admitted size")
|
||||
if response.status not in (200, 201):
|
||||
try:
|
||||
@@ -98,7 +100,7 @@ class CoreClient:
|
||||
PREFIX + "/worlds/" + world["world_id"] + "/source.ply", world, target, pulse=pulse
|
||||
)
|
||||
|
||||
def download_asset(self, path: str, descriptor: dict, target: Path, pulse=None):
|
||||
def download_asset(self, path: str, descriptor: dict, target: Path, pulse=None, *, authenticated=False):
|
||||
if not path.startswith("/api/v1/") or ".." in path or "\\" in path:
|
||||
raise ValueError("Invalid Core asset path")
|
||||
world = descriptor
|
||||
@@ -109,7 +111,8 @@ class CoreClient:
|
||||
try:
|
||||
if pulse:
|
||||
pulse()
|
||||
connection.request("GET", path)
|
||||
connection.request("GET", path, headers={"Authorization": "Bearer " + self.token}
|
||||
if authenticated else {})
|
||||
response = connection.getresponse()
|
||||
if pulse:
|
||||
pulse()
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Exact-identity Docker lifecycle for the separately packaged mapping module."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from local_state import read_json, write_json
|
||||
|
||||
|
||||
def docker(*args, check=True):
|
||||
result = subprocess.run(
|
||||
["docker", *map(str, args)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=30,
|
||||
)
|
||||
if check and result.returncode:
|
||||
raise RuntimeError("Infrastructure Docker operation failed: " + result.stderr[-1000:])
|
||||
return result
|
||||
|
||||
|
||||
def inspect_owned(name, key):
|
||||
result = docker("container", "inspect", name, check=False)
|
||||
if result.returncode:
|
||||
# Prove absence from a successful daemon listing; a dead daemon is not absence.
|
||||
ids = docker("ps", "-aq", "--filter", "name=^/" + name + "$").stdout.strip()
|
||||
if ids:
|
||||
raise RuntimeError("Cannot inspect analysis container")
|
||||
return None
|
||||
row = json.loads(result.stdout)[0]
|
||||
labels = row["Config"].get("Labels") or {}
|
||||
if (
|
||||
labels.get("com.nodedc.analysis") != key
|
||||
or labels.get("com.nodedc.stack") != "urban-mapping"
|
||||
):
|
||||
raise RuntimeError("Analysis container identity changed")
|
||||
return row
|
||||
|
||||
|
||||
def cleanup(marker):
|
||||
record = read_json(marker)
|
||||
if not record:
|
||||
return
|
||||
for name in list(record["containers"]):
|
||||
row = inspect_owned(name, record["key"])
|
||||
if row:
|
||||
docker("rm", "-f", row["Id"])
|
||||
if inspect_owned(name, record["key"]):
|
||||
raise RuntimeError("Analysis container was not released")
|
||||
# Retain only unresolved ownership, not every historical stage. Exit
|
||||
# receipts hold history; rescanning it made long pipelines quadratic.
|
||||
record["containers"].remove(name)
|
||||
write_json(marker, record)
|
||||
|
||||
|
||||
def resource_arguments(resources=None):
|
||||
"""Bound one owned container; never alter Docker or host-wide limits."""
|
||||
values={"cpus":4,"memory_gib":16}
|
||||
if resources is not None:
|
||||
if not isinstance(resources,dict) or set(resources)-set(values):
|
||||
raise ValueError("Unsupported infrastructure resource profile")
|
||||
values.update(resources)
|
||||
for key,lower,upper in [("cpus",1,12),("memory_gib",8,32)]:
|
||||
if type(values[key])is not int or not lower<=values[key]<=upper:
|
||||
raise ValueError("Infrastructure resource limit out of bounds: "+key)
|
||||
return ["--cpus",str(values["cpus"]),"--memory",str(values["memory_gib"])+"g"]
|
||||
|
||||
|
||||
def run_container(marker, phase, image, mounts, command, output, pulse, timeout, *,
|
||||
gpu=True, executable=None, environment=None, volumes=(), readonly=False, resources=None):
|
||||
resource_args = resource_arguments(resources)
|
||||
record = read_json(marker)
|
||||
name = "ndc-infrastructure-" + record["key"][:16] + "-" + phase
|
||||
if name not in record["containers"]:
|
||||
record["containers"].append(name)
|
||||
write_json(marker, record) # Persist intent before Docker creation.
|
||||
previous = inspect_owned(name, record["key"])
|
||||
if previous:
|
||||
raise RuntimeError("Unreconciled analysis container")
|
||||
config = json.loads(docker("image", "inspect", image).stdout)[0]["Config"]
|
||||
inherited = next(
|
||||
(e.partition("=")[2] for e in config.get("Env", []) if e.startswith("PYTHONPATH=")), ""
|
||||
)
|
||||
pythonpath = "/geometry:/app:/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e"
|
||||
if inherited:
|
||||
pythonpath += ":" + inherited
|
||||
args = [
|
||||
"create",
|
||||
"--name",
|
||||
name,
|
||||
"--network",
|
||||
"none",
|
||||
*resource_args,
|
||||
"--shm-size",
|
||||
"1g",
|
||||
"--label",
|
||||
"com.nodedc.product=mission-core",
|
||||
"--label",
|
||||
"com.nodedc.stack=urban-mapping",
|
||||
"--label",
|
||||
"com.nodedc.role=" + phase,
|
||||
"--label",
|
||||
"com.nodedc.managed-by=infrastructure-worker",
|
||||
"--label",
|
||||
"com.nodedc.analysis=" + record["key"],
|
||||
"-e",
|
||||
"PYTHONDONTWRITEBYTECODE=1",
|
||||
"-e",
|
||||
"PYTHONFAULTHANDLER=1",
|
||||
"-e",
|
||||
"OMP_NUM_THREADS=4",
|
||||
"-e",
|
||||
"PYTHONPATH=" + pythonpath,
|
||||
]
|
||||
if gpu:
|
||||
args += ["--gpus", "all"]
|
||||
if readonly:
|
||||
args += ["--read-only", "--pids-limit", "512", "--cap-drop", "ALL",
|
||||
"--security-opt", "no-new-privileges", "--tmpfs", "/tmp:rw,exec,size=1g"]
|
||||
for variable, value in (environment or {}).items():
|
||||
if variable == "PYTHONPATH":
|
||||
value = value + (":" + inherited if inherited else "")
|
||||
args += ["-e", variable + "=" + str(value)]
|
||||
for volume, destination in volumes:
|
||||
if not volume.startswith("ndc-"):
|
||||
raise ValueError("Analysis cache volume requires owned namespace")
|
||||
args += ["--mount", "type=volume,source=" + volume + ",target=" + destination]
|
||||
for source, destination, readonly in mounts:
|
||||
args += [
|
||||
"--mount",
|
||||
"type=bind,source="
|
||||
+ str(Path(source).resolve())
|
||||
+ ",target="
|
||||
+ destination
|
||||
+ (",readonly" if readonly else ""),
|
||||
]
|
||||
exe = executable or ("/usr/bin/python3" if phase == "survey" else "/opt/conda/envs/goose/bin/python")
|
||||
args += ["--entrypoint", exe, image, *command]
|
||||
cid = docker(*args).stdout.strip()
|
||||
row = inspect_owned(name, record["key"])
|
||||
if not row or row["Id"] != cid:
|
||||
raise RuntimeError("Docker create identity mismatch")
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
docker("start", cid)
|
||||
while True:
|
||||
pulse()
|
||||
row = inspect_owned(name, record["key"])
|
||||
if not row:
|
||||
raise RuntimeError("Analysis container disappeared")
|
||||
if not row["State"]["Running"]:
|
||||
logs = docker("logs", "--tail", "2000", cid, check=False)
|
||||
(output / (phase + ".log")).write_text(logs.stdout + logs.stderr, encoding="utf-8")
|
||||
write_json(output / (phase + "-exit.json"), row["State"])
|
||||
if row["State"]["ExitCode"]:
|
||||
state = row["State"]
|
||||
raise RuntimeError(
|
||||
f"Analysis {phase} exited {state['ExitCode']}; OOM={state['OOMKilled']}"
|
||||
)
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("Infrastructure analysis exceeded its bounded runtime")
|
||||
time.sleep(1)
|
||||
finally:
|
||||
cleanup(marker)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Final map admission runs inside the pinned scientific runtime, not host Python."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from k1link.simulation.ai_polygon.qualified_maps import qualified_document
|
||||
|
||||
root = Path('/analysis')
|
||||
request = json.loads((root/'publication-request.json').read_bytes())
|
||||
plan = root/request['plan']
|
||||
if not plan.resolve().is_relative_to(root.resolve()):
|
||||
raise ValueError('Analysis plan escaped owned output')
|
||||
raw = plan.read_bytes()
|
||||
count = len(json.loads((root/'ortho/survey/tile-index.json').read_bytes())['tiles'])
|
||||
document = qualified_document(raw, request['world'],
|
||||
artifact_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
source_world_sha256=request['world']['sha256'],
|
||||
qualification='analysis-'+request['key'][:16],
|
||||
source_snapshot=request['snapshot'], tiles_total=count)
|
||||
document['analysis'].update(job_key=request['key'], provider_sha256=request['provider'])
|
||||
(root/'urban-map.json').write_text(json.dumps(document, allow_nan=False),encoding='utf-8')
|
||||
@@ -0,0 +1,228 @@
|
||||
"""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
|
||||
@@ -0,0 +1,225 @@
|
||||
"""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
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Whole-scene Gaussian/trajectory analysis with owned Worker lifecycle."""
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from core_client import CoreRequestRejected
|
||||
from infrastructure_containers import cleanup, docker, run_container
|
||||
from infrastructure_gaussian_sources import prepare_native
|
||||
from infrastructure_pipeline import MODULE, run_pipeline
|
||||
from infrastructure_sources import checksum
|
||||
from infrastructure_transport import registered_request, report_progress, unavailable
|
||||
from local_state import read_json, write_json
|
||||
|
||||
from k1link.simulation.ai_polygon.infrastructure_jobs import provider_identity
|
||||
|
||||
|
||||
def capability(state):
|
||||
profile = json.loads((MODULE / "pipeline/worker-profile.json").read_text())
|
||||
runtime = Path(state).parent
|
||||
try:
|
||||
for key in ("mapper_image", "semantic_image"):
|
||||
actual = docker("image", "inspect", profile[key], "--format", "{{.Id}}").stdout.strip()
|
||||
if actual != profile[key]:
|
||||
return None
|
||||
import runpy
|
||||
|
||||
for pin in runpy.run_path(str(MODULE / "catalog_pass/catalog_dependency_pins.py"))["PINS"]:
|
||||
if checksum(MODULE / "pipeline/vendor" / pin["file"]) != pin["sha256"]:
|
||||
return None
|
||||
for path in [runtime / profile["splat_transform"], Path(profile["sevenzip"])]:
|
||||
if not path.is_file():
|
||||
return None
|
||||
cfg = read_json(MODULE / "pipeline/config-mv.json")
|
||||
for model in cfg["models"].values():
|
||||
for name, sha in model["files"].items():
|
||||
if checksum(runtime / model["directory"] / name) != sha:
|
||||
return None
|
||||
model = read_json(Path(__file__).with_name("sam3-research") / "large-model.json")
|
||||
for name, sha in model["files"].items():
|
||||
if checksum(runtime / profile["semantic_model"] / name) != sha:
|
||||
return None
|
||||
return provider_identity()
|
||||
except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired):
|
||||
logging.exception("Gaussian infrastructure capability is unavailable")
|
||||
return None
|
||||
|
||||
|
||||
def reconcile(client, marker, hello=None):
|
||||
record = read_json(marker)
|
||||
if not record:
|
||||
return
|
||||
cleanup(marker)
|
||||
record = read_json(marker)
|
||||
endpoint = "/worker/infrastructure-analysis/" + record["key"]
|
||||
if record.get("completion"):
|
||||
# The result outbox is durable before the first HTTP attempt. Replaying
|
||||
# identical complete is validated/idempotent at Core, including lost ACKs.
|
||||
output = (
|
||||
Path(read_json(MODULE / "pipeline/worker-profile.json")["job_root"]) / record["key"]
|
||||
)
|
||||
document = output / "urban-map.json"
|
||||
if checksum(document) != record["completion"]["sha256"]:
|
||||
raise ValueError("Pending infrastructure result changed")
|
||||
try:
|
||||
registered_request(
|
||||
client, endpoint, dict(action="complete", map=read_json(document)), hello=hello
|
||||
)
|
||||
except CoreRequestRejected as exc:
|
||||
if exc.status != 400 and not (
|
||||
exc.status == 409
|
||||
and exc.detail
|
||||
in ("Analysis cancellation requested", "Analysis is not owned by this worker")
|
||||
):
|
||||
raise
|
||||
# A confirmed cancellation/validation rejection is terminal, unlike
|
||||
# an unavailable Core. Preserve evidence; never publish around it.
|
||||
write_json(
|
||||
output / "publication-rejection.json", dict(status=exc.status, detail=exc.detail)
|
||||
)
|
||||
record.pop("completion")
|
||||
write_json(marker, record)
|
||||
registered_request(
|
||||
client, endpoint, dict(action="release", previous_owner=record["owner"]), hello=hello
|
||||
)
|
||||
marker.unlink()
|
||||
|
||||
|
||||
def source_package(client, endpoint, pulse, deadline):
|
||||
# This is a read, so an interrupted response may safely be fetched again.
|
||||
while True:
|
||||
pulse()
|
||||
try:
|
||||
return client.request(endpoint, max_response_bytes=24 * 1024**2)
|
||||
except Exception as exc:
|
||||
if not unavailable(exc):
|
||||
raise
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError(
|
||||
"Infrastructure source wait exceeded its runtime budget"
|
||||
) from exc
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def prepare_infrastructure(client, row, state, marker, hello=None):
|
||||
state = Path(state)
|
||||
profile = read_json(MODULE / "pipeline/worker-profile.json")
|
||||
if row["identity"]["provider_sha256"] != provider_identity():
|
||||
raise ValueError("Infrastructure provider changed")
|
||||
runtime = state.parent
|
||||
output = Path(profile["job_root"]) / row["key"]
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
write_json(marker, dict(key=row["key"], owner=client.instance, containers=[]))
|
||||
endpoint = "/worker/infrastructure-analysis/" + row["key"]
|
||||
last_pulse = -float("inf")
|
||||
connected = True
|
||||
phase = dict(phase="preparing", completed=0, total=0)
|
||||
|
||||
def pulse():
|
||||
nonlocal last_pulse, phase, connected
|
||||
if time.monotonic() - last_pulse < 3:
|
||||
return
|
||||
progress = output / "progress.json"
|
||||
if progress.exists():
|
||||
with contextlib.suppress(ValueError, OSError):
|
||||
phase = read_json(progress)
|
||||
response = report_progress(client, endpoint, phase, hello=hello)
|
||||
online = response is not None
|
||||
if online != connected:
|
||||
logging.warning(
|
||||
"Infrastructure control %s; local computation retained",
|
||||
"restored" if online else "unavailable",
|
||||
)
|
||||
connected = online
|
||||
last_pulse = time.monotonic()
|
||||
|
||||
try:
|
||||
if shutil.disk_usage(output).free < profile["minimum_free_gib"] * 1024**3:
|
||||
raise RuntimeError("Insufficient space for Gaussian analysis results")
|
||||
pulse()
|
||||
package = source_package(
|
||||
client,
|
||||
"/worker/worlds/" + row["world"]["world_id"] + "/infrastructure-source",
|
||||
pulse,
|
||||
time.monotonic() + profile["maximum_seconds"],
|
||||
)
|
||||
inputs, source = prepare_native(package, row["world"], state, profile, pulse, client=client)
|
||||
plan, snapshot = run_pipeline(inputs, source, output, marker, profile, runtime, pulse)
|
||||
if row["identity"]["provider_sha256"] != provider_identity():
|
||||
raise ValueError("Infrastructure provider changed during execution")
|
||||
write_json(
|
||||
output / "publication-request.json",
|
||||
dict(
|
||||
plan=plan.relative_to(output).as_posix(),
|
||||
world=row["world"],
|
||||
key=row["key"],
|
||||
snapshot=snapshot,
|
||||
provider=row["identity"]["provider_sha256"],
|
||||
),
|
||||
)
|
||||
release = Path(__file__).resolve().parents[2]
|
||||
run_container(
|
||||
marker,
|
||||
"publication",
|
||||
profile["mapper_image"],
|
||||
[(release, "/release", True), (output, "/analysis", False)],
|
||||
["-B", "/release/simulation/ai-polygon/infrastructure_document.py"],
|
||||
output,
|
||||
pulse,
|
||||
300,
|
||||
gpu=False,
|
||||
executable="python3",
|
||||
environment={"PYTHONPATH": "/release/src"},
|
||||
readonly=True,
|
||||
)
|
||||
record = read_json(marker)
|
||||
record["completion"] = dict(sha256=checksum(output / "urban-map.json"))
|
||||
write_json(marker, record)
|
||||
except Exception as exc:
|
||||
logging.exception("Infrastructure analysis failed")
|
||||
write_json(output / "failure.json", dict(type=type(exc).__name__, message=str(exc)))
|
||||
try:
|
||||
registered_request(client, endpoint, dict(action="fail"), hello=hello)
|
||||
except Exception:
|
||||
logging.warning("Infrastructure failure receipt awaits reconciliation")
|
||||
finally:
|
||||
try:
|
||||
reconcile(client, marker, hello)
|
||||
except Exception:
|
||||
# Keep the durable marker. The coordinator's existing reconnect loop
|
||||
# retries cleanup/release before polling any subsequent job.
|
||||
logging.exception("Infrastructure release awaits reconciliation")
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Read-only source resolution. Analysis never copies or downloads a scene."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def checksum(path, pulse=lambda: None):
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(8 * 1024**2), b""):
|
||||
h.update(block)
|
||||
pulse()
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def resolve_sources(world, state, pulse=lambda: None):
|
||||
"""Reuse the simulator's verified complete-scene artifact, including its frame.
|
||||
|
||||
Missing assets are a producer/preparation error, never permission to clone a
|
||||
Gaussian Pipeline package into the mapping job. No mkdir or file writes here.
|
||||
"""
|
||||
root = (Path(state) / "project-packages" / world["sha256"]).resolve()
|
||||
terrain_path = root / "terrain.json"
|
||||
if not terrain_path.is_file():
|
||||
raise ValueError("Worker has no prepared shared scene; prepare this location first")
|
||||
terrain = json.loads(terrain_path.read_text(encoding="utf-8"))
|
||||
if (
|
||||
terrain.get("source_sha256") != world["sha256"]
|
||||
or terrain.get("source_collider_sha256") != world["collider_sha256"]
|
||||
or terrain.get("collision_rotation") != world["local_scene"]["collision_rotation"]
|
||||
):
|
||||
raise ValueError("Shared scene calibration or collider changed")
|
||||
collider = root / (world["collider_sha256"] + ".decoded.glb")
|
||||
metadata = json.loads(collider.with_suffix(".json").read_text(encoding="utf-8"))
|
||||
if (
|
||||
metadata["source_sha256"] != world["collider_sha256"]
|
||||
or checksum(collider, pulse) != metadata["sha256"]
|
||||
):
|
||||
raise ValueError("Shared collider checksum mismatch")
|
||||
candidates = []
|
||||
for path in root.glob("*.json"):
|
||||
if path == terrain_path or path.name.endswith(".decoded.json"):
|
||||
continue
|
||||
row = json.loads(path.read_text(encoding="utf-8"))
|
||||
source = path.with_suffix(".ply")
|
||||
if (
|
||||
row.get("source_sha256") == world["sha256"]
|
||||
and row.get("coverage") == "complete-source"
|
||||
and row.get("spatially_cropped") is False
|
||||
and source.is_file()
|
||||
):
|
||||
candidates.append((row.get("lod", 0), source, row))
|
||||
if not candidates:
|
||||
raise ValueError("Worker has no verified complete shared Gaussian representation")
|
||||
# Preserve the best representation already present. No new LOD conversion.
|
||||
lod, source, receipt = sorted(candidates, key=lambda c: c[0])[0]
|
||||
if source.is_symlink() or collider.is_symlink() or checksum(source, pulse) != receipt["sha256"]:
|
||||
raise ValueError("Shared Gaussian source changed")
|
||||
return root, dict(
|
||||
ply=source.name,
|
||||
sha256=receipt["sha256"],
|
||||
lod=lod,
|
||||
world_sha256=world["sha256"],
|
||||
collider_sha256=world["collider_sha256"],
|
||||
source_to_world=[[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]],
|
||||
)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Reuse verified survey derivatives across vectorizer releases without copying them."""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from local_state import read_json, write_json
|
||||
|
||||
|
||||
def file_hash(path):
|
||||
result = hashlib.sha256()
|
||||
with Path(path).open('rb') as stream:
|
||||
for block in iter(lambda: stream.read(8 * 1024**2), b''):
|
||||
result.update(block)
|
||||
return result.hexdigest()
|
||||
|
||||
|
||||
def survey_identity(module, terrain, profile):
|
||||
# Vector code may change without invalidating the measured survey. All code
|
||||
# that creates cameras, renders, segments or projects ground remains bound.
|
||||
files = {name: file_hash(module / name) for name in
|
||||
('whole_scene.py', 'mapping.py', 'atlas.py', 'job.example.json')}
|
||||
files['terrain.py'] = file_hash(terrain)
|
||||
content = dict(files=files, mapper_image=profile['mapper_image'],
|
||||
semantic_model=profile['semantic_model'])
|
||||
return hashlib.sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def verify_tiles(folder, request, pulse):
|
||||
index = read_json(folder / 'tile-index.json')
|
||||
if not index or not 0 < len(index.get('tiles', [])) <= 256:
|
||||
raise ValueError('Missing completed survey index')
|
||||
for tile in index['tiles']:
|
||||
pulse()
|
||||
if not re.fullmatch(r'tile-\d{3}-\d{3}', tile['id']):
|
||||
raise ValueError('Invalid survey tile path')
|
||||
if tile['status'] == 'no-surface':
|
||||
continue
|
||||
if tile['status'] not in ('surveyed', 'unobserved-ground'):
|
||||
raise ValueError('Survey is incomplete')
|
||||
part = folder / tile['id']
|
||||
receipt = read_json(part / 'survey-receipt.json')
|
||||
job = read_json(part / 'job.json')
|
||||
if (not receipt or not job or receipt['status'] != tile['status']
|
||||
or receipt['job_sha256'] != file_hash(part / 'job.json')
|
||||
or job['source'] != request['source'] or job['model'] != request['model']):
|
||||
raise ValueError('Survey input identity changed')
|
||||
if set(receipt['files']) != {'top.png', 'top.geometry.npz', 'surface-atlas.npz'}:
|
||||
raise ValueError('Unexpected survey artifacts')
|
||||
for name, expected in receipt['files'].items():
|
||||
if file_hash(part / name) != expected:
|
||||
raise ValueError('Survey artifact changed')
|
||||
return index
|
||||
|
||||
|
||||
def record_survey(folder, request, identity, pulse):
|
||||
verify_tiles(folder, request, pulse)
|
||||
write_json(folder / 'survey-cache.json', dict(
|
||||
schema_version='missioncore.infrastructure-survey-cache/v1',
|
||||
survey_sha256=identity, source=request['source'], model=request['model'],
|
||||
index_sha256=file_hash(folder / 'tile-index.json')))
|
||||
|
||||
|
||||
def find_survey(jobs, request, identity, pulse):
|
||||
for path in sorted(jobs.glob('*/survey-cache.json')):
|
||||
try:
|
||||
record = read_json(path)
|
||||
if (record['schema_version'] != 'missioncore.infrastructure-survey-cache/v1'
|
||||
or record['survey_sha256'] != identity
|
||||
or record['source'] != request['source'] or record['model'] != request['model']
|
||||
or record['index_sha256'] != file_hash(path.parent / 'tile-index.json')):
|
||||
continue
|
||||
verify_tiles(path.parent, request, pulse)
|
||||
return path.parent
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
continue
|
||||
return None
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Infrastructure observations survive control-plane loss; commands stay fenced."""
|
||||
|
||||
import http.client
|
||||
|
||||
from core_client import CoreRequestRejected
|
||||
|
||||
EXPIRED_SESSION = "Сессия Worker истекла; требуется переподключение."
|
||||
|
||||
|
||||
def unavailable(exc):
|
||||
return isinstance(exc, (OSError, http.client.HTTPException)) or (
|
||||
isinstance(exc, CoreRequestRejected) and 500 <= exc.status <= 599
|
||||
)
|
||||
|
||||
|
||||
def registered_request(client, endpoint, body=None, *, hello=None, **kwargs):
|
||||
"""Retry only an explicit pre-execution session rejection, with the same owner.
|
||||
|
||||
Callers use this for reads and idempotent observations/receipts, never dispatch.
|
||||
A cancellation, changed owner or invalid result is not a transport outage.
|
||||
"""
|
||||
try:
|
||||
return client.request(endpoint, body, **kwargs)
|
||||
except CoreRequestRejected as exc:
|
||||
if exc.status != 409 or exc.detail != EXPIRED_SESSION or hello is None:
|
||||
raise
|
||||
if hello["instance_id"] != client.instance:
|
||||
raise ValueError("Infrastructure reconnect owner changed") from exc
|
||||
client.request("/worker/register", hello)
|
||||
return client.request(endpoint, body, **kwargs)
|
||||
|
||||
|
||||
def report_progress(client, endpoint, phase, *, hello=None):
|
||||
# A missed observation must never unwind run_container's cleanup guard.
|
||||
# The next pulse sends the latest local progress, without a growing queue.
|
||||
try:
|
||||
return registered_request(client, endpoint, dict(action="progress", **phase), hello=hello)
|
||||
except Exception as exc:
|
||||
if not unavailable(exc):
|
||||
raise
|
||||
return None
|
||||
@@ -260,7 +260,10 @@ def main():
|
||||
}
|
||||
from k1link.simulation.ai_polygon.route_preparation import provider_identity
|
||||
|
||||
from infrastructure_preparer import capability, prepare_infrastructure, reconcile
|
||||
|
||||
hello = {
|
||||
"infrastructure_provider_sha256": capability(args.state),
|
||||
"route_provider_sha256": provider_identity(),
|
||||
"worker_id": "worker-006-ai-polygon",
|
||||
"instance_id": instance,
|
||||
@@ -346,8 +349,10 @@ def main():
|
||||
connect()
|
||||
editor_marker = args.state / "editor-active.json"
|
||||
route_marker = args.state / "route-active.json"
|
||||
infrastructure_marker = args.state / "infrastructure-active.json"
|
||||
while True:
|
||||
try:
|
||||
reconcile(client, infrastructure_marker, hello)
|
||||
# A prior coordinator's Windows Job killed all native descendants on exit.
|
||||
# Retain the marker until Core accepts that resource-release receipt.
|
||||
if route_marker.exists():
|
||||
@@ -361,6 +366,9 @@ def main():
|
||||
polled = client.request("/worker/poll", {"instance_id": instance})
|
||||
except Exception:
|
||||
connect()
|
||||
# A pending receipt may fail while registration succeeds. Bound
|
||||
# retries without discarding its marker or busy-looping on Core.
|
||||
time.sleep(3)
|
||||
continue
|
||||
if polled["action"] == "idle":
|
||||
time.sleep(0.5)
|
||||
@@ -386,6 +394,9 @@ def main():
|
||||
editor_job.close()
|
||||
# Receipt is sent at the top of the loop, after the Job is closed.
|
||||
continue
|
||||
if polled["action"] == "infrastructure-analysis":
|
||||
prepare_infrastructure(client, polled["analysis"], args.state, infrastructure_marker, hello)
|
||||
continue
|
||||
run = polled["run"]
|
||||
if run.get("clock") != "realtime":
|
||||
raise RuntimeError("A realtime worker cannot execute lockstep work")
|
||||
|
||||
Reference in New Issue
Block a user