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:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent 25dc0a1b44
commit f48411f8fe
116 changed files with 10690 additions and 263 deletions
@@ -103,6 +103,19 @@ class PlanLibraryUpdate(Contract):
removed: bool | None = Field(default=None, strict=True)
class WorldLibraryUpdate(Contract):
display_name: str | None = Field(default=None, min_length=1, max_length=120)
removed: bool | None = Field(default=None, strict=True)
@model_validator(mode="after")
def require_change(self):
if self.display_name is None and self.removed is None:
raise ValueError("Укажите название или действие с локацией.")
if self.display_name and any(ord(c) < 32 for c in self.display_name):
raise ValueError("Название содержит недопустимые символы.")
return self
class WorkerWorldCreate(WorldCreate):
"""Attestation from the connected Worker after validating its local files."""
@@ -151,6 +164,7 @@ class WorkerHello(Contract):
rover_settings_versions: list[Literal["missioncore.rover-settings/v1", "missioncore.rover-settings/v2"]] = Field(
default_factory=list, max_length=2
)
infrastructure_provider_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
route_provider_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
execution_inputs_versions: list[
Literal[
@@ -0,0 +1,332 @@
"""Durable, content-bound whole-scene analysis using the simulation GPU reservation."""
import hashlib
import json
import re
import threading
import time
import uuid
from pathlib import Path
from .run_inputs import digest
def write_json(path, value):
# The Windows coordinator imports provider_identity before any model runtime.
from .worlds import write_json as persist
persist(path, value)
def provider_identity():
root = Path(__file__).resolve().parents[4]
module = root / "simulation/urban-mapping"
files = [
p
for p in module.rglob("*")
if p.is_file()
and p.suffix in {".py", ".json"}
and ".build" not in p.parts
and "__pycache__" not in p.parts
]
files += [
*[
root / ("simulation/ai-polygon/" + n + ".py")
for n in (
"infrastructure_preparer",
"infrastructure_transport",
"infrastructure_sources",
"infrastructure_survey_cache",
"infrastructure_containers",
"core_client",
"terrain",
)
]
]
# Exact declared algorithm closure, including presets and metric policies.
research = root / "simulation/urban-plan-research"
definition = json.loads((research / "pipeline/definition.json").read_text(encoding="utf-8"))
relative = {value for group in definition["groups"] for value in group["files"].values()}
relative.update(
{
"pipeline/definition.json",
"pipeline/config-mv.json",
"pipeline/config-ortho.json",
"pipeline/worker-profile.json",
}
)
files += [research / name for name in sorted(relative)]
files += [
root / "simulation/ai-polygon" / (name + ".py")
for name in (
"infrastructure_pipeline",
"infrastructure_gaussian_sources",
"infrastructure_document",
)
]
return digest(
{p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files}
)
class InfrastructureJobs:
def __init__(self, data_dir):
self.root = Path(data_dir) / "ai-polygon/infrastructure-jobs"
self.root.mkdir(parents=True, exist_ok=True)
self.lock = threading.RLock()
def path(self, key):
if not re.fullmatch("[a-f0-9]{64}", key):
raise ValueError("Invalid analysis identity")
return self.root / (key + ".json")
def get(self, key):
row = json.loads(self.path(key).read_text(encoding="utf-8"))
if row["key"] != key or digest(row["identity"]) != key:
raise ValueError("Analysis identity changed")
return row
def current(self, world):
provider = provider_identity()
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
rows = [
r
for r in rows
if r["identity"]["world_sha256"] == world["sha256"]
and r["identity"]["collider_sha256"] == world.get("collider_sha256")
and r["identity"]["provider_sha256"] == provider
]
return max(rows, key=lambda r: r["created_at"], default=None)
def request(self, world, force=False, request_id=None):
with self.lock:
if not world.get("local_scene"):
raise ValueError(
"Для анализа нужен исходный Gaussian-проект с маршрутом сканирования."
)
identity = dict(
world_sha256=world["sha256"],
collider_sha256=world.get("collider_sha256"),
scene=world["local_scene"],
provider_sha256=provider_identity(),
scope="whole-scene",
)
# Force creates a new content-bound generation, never overwrites the
# old ready map. Retried HTTP requests share one request identity.
if force:
if not isinstance(request_id, str) or not re.fullmatch("[a-f0-9]{32}", request_id):
raise ValueError("A recalculation requires a request identity")
identity["generation"] = request_id
key = digest(identity)
if force and self.path(key).exists():
return self.get(key)
current = self.current(world)
if current and (
current["status"] in ("queued", "running") or not current.get("released", True)
):
return current
if not force and current and current["status"] == "ready":
return current
if self.path(key).exists():
row = self.get(key)
if row["status"] not in ("failed", "cancelled") or not row.get("released", True):
return row
return self.request(world, True, request_id or uuid.uuid4().hex)
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
if (
sum(
r["status"] in ("queued", "running") or not r.get("released", True)
for r in rows
)
>= 32
):
raise RuntimeError(
"Очередь заполнена: дождитесь завершения или отмените лишние расчёты."
)
sequence = max((r.get("queue_sequence", 0) for r in rows), default=0) + 1
row = dict(
queue_sequence=sequence,
key=key,
identity=identity,
world=world,
status="queued",
owner=None,
phase="queued",
completed=0,
total=0,
error=None,
result=None,
created_at=time.time(),
released=True,
)
write_json(self.path(key), row)
return row
def pending(self):
with self.lock:
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
# A source-tree digest is only needed to admit queued work. Idle
# worker polls and cleanup must not repeatedly hash the module.
provider = provider_identity() if any(r["status"] == "queued" for r in rows) else None
for row in rows:
if row["status"] == "queued" and row["identity"]["provider_sha256"] != provider:
row.update(
status="failed", error="Модуль анализа обновлён. Запустите анализ заново."
)
write_json(self.path(row["key"]), row)
rows = [
r
for r in rows
if r["status"] in ("queued", "running") or not r.get("released", True)
]
# Cleanup ownership precedes waiting jobs, including after a crash.
return min(rows, key=self.queue_order, default=None)
@staticmethod
def queue_order(row):
return (
0 if not row.get("released", True) else 1,
row.get("queue_sequence", 0),
row["created_at"],
row["key"],
)
def queue_rows(self):
with self.lock:
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
return sorted(
[
r
for r in rows
if r["status"] in ("queued", "running") or not r.get("released", True)
],
key=self.queue_order,
)
def present(self, row):
if not row:
return None
result = public_job(row)
rows = self.queue_rows()
keys = [r["key"] for r in rows]
result["queue"] = dict(
position=keys.index(row["key"]) + 1 if row["key"] in keys else None,
total=len(rows),
waiting=sum(r["status"] == "queued" for r in rows),
)
if row.get("cancel_requested") and not row.get("released", True):
result["progress"].update(
label="Отмена · освобождаем Worker", eta_seconds=None, fraction=None
)
return result
def cancel(self, key):
with self.lock:
row = self.get(key)
if row["status"] in ("ready", "failed", "cancelled"):
return row
row["cancel_requested"] = True
row["cancel_requested_at"] = time.time()
if row["status"] == "queued":
row.update(status="cancelled", phase="cancelled", finished_at=time.time())
# Running stays owned until the worker's existing finally/cleanup
# sends release. A progress rejection interrupts its bounded stage.
write_json(self.path(key), row)
return row
def dispatch(self, owner, queue, worker_provider):
# Keep selection, GPU reservation and claim atomic with cancellation.
# Otherwise cancellation between reserve and claim strands the lease.
with self.lock:
row = self.pending()
if not row or row["status"] not in ("queued", "running"):
return None
if row["identity"]["provider_sha256"] != worker_provider:
return None
if row.get("cancel_requested") or row["owner"] not in (None, owner):
return None
queue.reserve_simulation("aicache-" + row["key"])
return self.claim(row["key"], owner)
def claim(self, key, owner):
with self.lock:
row = self.get(key)
pending = self.pending()
if not pending or pending["key"] != key:
raise RuntimeError("Analysis must wait its FIFO turn")
if row.get("cancel_requested"):
raise RuntimeError("Analysis cancellation requested")
if row["owner"] not in (None, owner) or row["status"] not in ("queued", "running"):
raise RuntimeError("Analysis belongs to another Worker session")
row.setdefault("started_at", time.time())
row.update(status="running", owner=owner, released=False, updated_at=time.time())
write_json(self.path(key), row)
return row
def update(self, key, body, owner):
with self.lock:
row = self.get(key)
action = body.get("action")
if row["owner"] != owner and not (
action == "release" and body.get("previous_owner") == row["owner"]
):
raise RuntimeError("Analysis owner changed")
if row.get("cancel_requested") and action in ("progress", "complete"):
raise RuntimeError("Analysis cancellation requested")
if action == "progress" and row["status"] == "running":
phase = body.get("phase")
if phase not in ("preparing", "survey", "vectorizing", "assembling", "refining"):
raise ValueError("Invalid analysis phase")
done, total = body.get("completed", 0), body.get("total", 0)
if type(done) is not int or type(total) is not int or not 0 <= done <= total <= 256:
raise ValueError("Invalid analysis progress")
if row.get("total") and (total != row["total"] or done < row["completed"]):
raise ValueError("Analysis progress cannot move backwards")
from .infrastructure_progress import record_progress
record_progress(row, phase, done, total, time.time())
elif action == "complete" and row["status"] == "running":
row.update(
status="ready",
phase="ready",
result=body["result"],
error=None,
finished_at=time.time(),
)
elif action == "fail" and row["status"] != "ready":
row.update(
status="failed",
error=(
"Анализ не завершён. Предыдущая карта сохранена; можно повторить попытку."
),
)
elif action == "release":
if row["status"] == "running":
row.update(
status="failed",
error=(
"Worker прервал анализ. Предыдущая карта сохранена; повторите попытку."
),
)
row["released"] = True
else:
raise ValueError("Invalid analysis state transition")
if row.get("cancel_requested") and action in ("fail", "release"):
row.update(
status="cancelled", phase="cancelled", error=None, finished_at=time.time()
)
write_json(self.path(key), row)
return row
def public_job(row):
if not row:
return None
from .infrastructure_progress import progress_view
public = {
k: v for k, v in row.items() if k not in ("owner", "world", "identity", "stage_history")
}
public["request_id"] = row["identity"].get("generation")
public["progress"] = progress_view(row)
return public
@@ -0,0 +1,130 @@
"""Measured stage history and an explicitly approximate remaining-time forecast.
A historical full infrastructure run seeds weights, never the arrow-only path.
Progress counts completed stages; time never advances the completion fraction.
"""
import json
import math
import statistics
import time
from functools import lru_cache
from pathlib import Path
PHASES = {
"queued": "В очереди",
"preparing": "Подготовка локации",
"survey": "Обзор локации",
"vectorizing": "Распознавание инфраструктуры",
"assembling": "Сборка карты",
"refining": "Уточнение объектов",
"ready": "Готово",
}
def stage_label(group, stage):
if stage == "pose_survey":
return "Обзор локации"
if "render" in stage:
return "Построение видов сцены"
if "semantic" in stage or stage in ("mv_infer", "ortho_segment"):
return "Распознавание объектов"
if "audit" in stage or "verify" in stage or "admission" in stage:
return "Проверка объектов"
if "arrow" in group or "arrow" in stage:
return "Восстановление стрелок"
if "bicycle" in group or "compact" in stage:
return "Восстановление велоразметки"
if "cross" in group or "cross" in stage:
return "Восстановление переходов"
if "linear" in group or "zigzag" in group:
return "Восстановление линий"
if group == "base":
return "Определение поверхностей"
return "Согласование инфраструктуры"
@lru_cache(maxsize=1)
def plan():
root = Path(__file__).resolve().parents[4] / "simulation/urban-plan-research/pipeline"
definition = json.loads((root / "definition.json").read_text())
stages = [(g["group"], s) for g in definition["groups"] for s in g["stages"]]
profile = (
json.loads((root / "timing-profile.json").read_text())
if (root / "timing-profile.json").exists()
else {"stages": []}
)
measured = {
(("base" if r["group"] == "geometry" else r["group"]), r["stage"]): r["seconds"]
for r in profile["stages"]
}
fallback = statistics.median(measured.values()) if measured else None
return [
dict(
group=g,
stage=s,
label=stage_label(g, s),
seconds=measured.get((g, s), fallback),
measured=(g, s) in measured,
)
for g, s in stages
], profile.get("job_key")
def record_progress(row, phase, done, total, now):
previous = (row["phase"], row["completed"], row["total"])
if previous != (phase, done, total):
row["stage_started_at"] = now
history = row.setdefault("stage_history", [])
history.append(dict(phase=phase, completed=done, total=total, at=now))
if len(history) > 257:
raise ValueError("Analysis progress history exceeds stage budget")
if total and "pipeline_started_at" not in row:
row["pipeline_started_at"] = now
row.update(phase=phase, completed=done, total=total, updated_at=now)
def progress_view(row, now=None):
now = time.time() if now is None else now
stages, reference = plan()
total = len(stages)
done = row.get("completed", 0)
status = row["status"]
running = status == "running"
pending = status in ("queued", "running")
comparable = row.get("total", 0) in (0, total)
label = PHASES.get(row["phase"], "Расчёт инфраструктуры")
if running and row.get("total") == total:
label = stages[min(done, total - 1)]["label"]
stale = running and now - row.get("updated_at", row.get("started_at", now)) > 20
eta = None
basis = "previous-full-run"
if pending and comparable and all(s["seconds"] is not None for s in stages):
weights = [s["seconds"] for s in stages]
scale = 1.0
if running and done > 0 and row.get("pipeline_started_at") is not None:
completed_seconds = max(
0, row.get("stage_started_at", now) - row["pipeline_started_at"]
)
baseline = sum(weights[:done])
if completed_seconds > 0 and baseline > 0:
scale = completed_seconds / baseline
basis = "current-run-and-history"
elapsed = (
max(0, now - row.get("stage_started_at", now)) if running and row.get("total") else 0
)
remaining = sum(weights[done:]) * scale - elapsed
# Never promise zero while a real stage is still running.
eta = max(60, math.ceil(remaining / 60) * 60)
return dict(
label="Нет обновлений от Worker" if stale else label,
stage=min(done + 1, total) if running and row.get("total") == total else None,
stages=total if comparable else row.get("total"),
fraction=done / total if running and row.get("total") == total else None,
eta_seconds=None if stale else eta,
eta_basis=basis,
estimate_reference=reference,
estimate_scope="processing-excludes-queue-and-source-preparation",
stale=stale,
elapsed_seconds=max(0, now - row["started_at"]) if "started_at" in row else None,
)
+1 -1
View File
@@ -5,7 +5,7 @@ import re
from k1link.simulation.ai_polygon.worlds import write_json
IDENTITY = re.compile(r"^(?:aiplan|airun)-[a-f0-9]{32}$")
IDENTITY = re.compile(r"^(?:aiplan|airun|aiworld)-[a-f0-9]{32}$")
class LibraryMetadata:
File diff suppressed because one or more lines are too long
@@ -47,6 +47,9 @@ class ProjectWorlds:
"artifacts": project["artifacts"],
}
digest = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
files = self.cache_files(
{"storage": {"project_id": project["project_id"]}, "local_scene": scene}
)
return {
"schema_version": "missioncore.ai-polygon-world/v1",
"world_id": project["project_id"].replace("sim-", "aiworld-", 1),
@@ -62,15 +65,14 @@ class ProjectWorlds:
"splat_count": None,
"created_at": project["created_at_utc"],
"settings": WorldSettings(
prepared=bool(scene["collision_url"]), rotation_degrees=(90, 0, 0)
prepared=True, rotation_degrees=(90, 0, 0)
).model_dump(mode="json"),
"storage": {"kind": "project", "project_id": project["project_id"]},
"local_scene": scene,
"collider_sha256": self.cache_files(
{"storage": {"project_id": project["project_id"]}, "local_scene": scene}
)["collision.glb"]["sha256"],
"inference_ready": True,
"collider_sha256": files.get("collision.glb", {}).get("sha256"),
"inference_ready": "collision.glb" in files,
"inference_message": None if "collision.glb" in files else
"Скан доступен для просмотра. Для запуска ровера нужна поверхность коллизий.",
}
def package(self, world):
@@ -78,6 +80,7 @@ class ProjectWorlds:
prefix = f"/api/v1/simulation-worlds/projects/{project['project_id']}/artifacts/"
paths = {
k: unquote(world["local_scene"][k + "_url"].removeprefix(prefix))
if world["local_scene"].get(k + "_url") else None
for k in ("visual", "collision")
}
artifacts = [
@@ -95,6 +98,55 @@ class ProjectWorlds:
"collision_path": paths["collision"],
}
def analysis_package(self, world):
"""Read original source identity and optional native trajectory, not meshes."""
import base64
project = self.projects.get(world["storage"]["project_id"])
if self.world(project)["sha256"] != world["sha256"]:
raise ValueError("Gaussian project changed")
source = project["source"]
result = dict(world_sha256=world["sha256"], project_id=project["project_id"],
provider_job_id=project["provider"]["job_id"],
bundle_sha256=source["bundle_sha256"], kind=source["kind"],
files=[{k: f[k] for k in ("logical_path", "byte_length", "sha256")}
for f in source["files"]], trajectory=None)
if source["kind"] == "folder":
from pathlib import PurePosixPath
candidates = [f for f in source["files"]
if PurePosixPath(f["logical_path"]).name.lower() == "poses.json"]
if len(candidates) != 1:
raise ValueError("Original Gaussian folder needs one poses.json")
item = candidates[0]
if not 0 < item["byte_length"] <= 16 * 1024**2:
raise ValueError("Trajectory exceeds analysis transport budget")
root = self.projects.source_root(project["project_id"]).resolve()
path = root / item["logical_path"]
if path.is_symlink() or not path.resolve().is_relative_to(root):
raise ValueError("Trajectory escaped its project")
raw = path.read_bytes()
if len(raw) != item["byte_length"] or hashlib.sha256(raw).hexdigest() != item["sha256"]:
raise ValueError("Original trajectory changed")
result["trajectory"] = dict(sha256=item["sha256"], byte_length=len(raw),
base64=base64.b64encode(raw).decode("ascii"))
return result
def analysis_archive(self, world):
"""Serve only the original archive belonging to this exact world."""
project = self.projects.get(world["storage"]["project_id"])
if self.world(project)["sha256"] != world["sha256"]:
raise ValueError("Gaussian project changed")
source = project["source"]
if source["kind"] != "archive" or len(source["files"]) != 1:
raise ValueError("Project does not contain one original archive")
descriptor = source["files"][0]
root = self.projects.source_root(project["project_id"]).resolve()
path = root / descriptor["logical_path"]
if path.is_symlink() or not path.resolve().is_relative_to(root):
raise ValueError("Original archive escaped its project")
if not path.is_file() or path.stat().st_size != descriptor["byte_length"]:
raise FileNotFoundError("Original archive is unavailable")
return path, descriptor
def cache_files(self, world):
result = {}
project_id = world["storage"]["project_id"]
@@ -103,6 +155,8 @@ class ProjectWorlds:
("scene.sog", world["local_scene"]["visual_url"]),
("collision.glb", world["local_scene"]["collision_url"]),
):
if name == "collision.glb" and not url:
continue
if not url or not url.startswith(prefix):
raise ValueError("В локации отсутствует локальная сцена или поверхность.")
path, descriptor = self.projects.artifact_path(project_id, unquote(url[len(prefix) :]))
@@ -0,0 +1,52 @@
"""Lossless admission of a qualified Gaussian plan to the existing viewer."""
import copy
import hashlib
import json
import re
from k1link.simulation.ai_polygon.urban_maps import validate_map
def qualified_document(raw: bytes, world: dict, *, artifact_sha256: str,
source_world_sha256: str, qualification: str,
source_snapshot: str, tiles_total: int) -> dict:
if hashlib.sha256(raw).hexdigest() != artifact_sha256:
raise ValueError("Qualified artifact content changed")
if source_world_sha256 != world["sha256"]:
raise ValueError("Qualified artifact belongs to another Gaussian scene")
if not re.fullmatch(r"[a-z0-9-]{1,100}", qualification):
raise ValueError("Invalid qualification identity")
if type(tiles_total) is not int or not 0 < tiles_total <= 10000:
raise ValueError("Invalid observed tile count")
plan = json.loads(raw)
if (plan.get("schema_version") not in {
"missioncore.refined-full-plan-research/v1", "missioncore.systematic-plan/v1"}
or plan.get("point_clouds") is not False
or plan.get("manual_geometry") is not False):
raise ValueError("Expected the qualified automatic Gaussian plan")
features = copy.deepcopy(plan["features"])
for feature in features:
p = feature["properties"]
if p.get("route_permission", "unassigned") != "unassigned":
raise ValueError("Plan cannot grant route permissions")
if p.get("authority", "observation-only") != "observation-only":
raise ValueError("Plan cannot escalate observation authority")
p["authority"] = "observation-only"
p["route_permission"] = "unassigned"
p.setdefault("review_status", "unreviewed")
if "confidence" not in p:
p.update(confidence=None, confidence_status="not-assessed")
result = {
"schema_version": "missioncore.urban-map/v3", "type": "FeatureCollection",
"coordinate_system": {"frame": "scene-local", "units": "metres", "up": "Z", "georeferenced": False},
"source": {"world_sha256": source_world_sha256,
"collider_sha256": world.get("collider_sha256"),
"gaussian_only": True, "collider_input": False,
"artifact_sha256": artifact_sha256,
"qualification": qualification, "source_snapshot": source_snapshot},
"coverage": {"cell_m": .05, "accepted_cells": 0, "kind": "objects-only", "measured": False},
"analysis": {"scope": "whole-scene", "tiles_total": tiles_total},
"logical_layers": ["roads", "pedestrian_zones", "buildings", "road_markings"],
"features": features,
}
return validate_map(result, world)
@@ -72,11 +72,20 @@ def write_json(path, row):
persist(path, row)
def _file_signature(path):
value = path.stat(follow_symlinks=False)
return (value.st_dev, value.st_ino, value.st_size,
value.st_mtime_ns, value.st_ctime_ns)
class RoutePreparationStore:
def __init__(self, data_dir):
self.root = Path(data_dir) / "ai-polygon/route-preparations"
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
self.lock = threading.RLock()
# Only inactive file metadata is cached. Active jobs and claims always
# re-read and validate their content and ownership.
self._inactive_files = {}
def path(self, key):
if not KEY.fullmatch(key):
@@ -122,10 +131,23 @@ class RoutePreparationStore:
def pending(self):
with self.lock:
for path in sorted(self.root.glob("*.json")):
paths = sorted(self.root.glob("*.json"))
present = {path.name for path in paths}
self._inactive_files = {name: stamp for name, stamp in self._inactive_files.items()
if name in present}
for candidate in paths:
path = self.path(candidate.stem)
before = _file_signature(path)
if self._inactive_files.get(path.name) == before:
continue
row = json.loads(path.read_text())
if row["status"] in {"queued", "preparing"}:
self._inactive_files.pop(path.name, None)
return self.get(path.stem)
if row["status"] in {"ready", "failed"} and before == _file_signature(path):
if len(self._inactive_files) >= 512:
self._inactive_files.pop(next(iter(self._inactive_files)))
self._inactive_files[path.name] = before
return None
def claim(self, key, owner):
+3 -1
View File
@@ -239,7 +239,9 @@ class RunStore:
raise RuntimeError("Контроль занятости Worker недоступен.")
if self.active is not None:
raise RuntimeError("Сначала завершите текущий прогон.")
world = self.worlds.get(request.world_id)
from .world_library import WorldLibrary
world = WorldLibrary(self.worlds).require_visible(request.world_id)
if world.get("inference_ready") is False:
raise RuntimeError(world["inference_message"])
if world.get("local_scene") and "project-sog" not in self.worker.get(
@@ -0,0 +1,470 @@
"""Small human map revisions. No images, training or automatic-map publication."""
import copy
import hashlib
import json
import math
import re
from datetime import UTC, datetime
from k1link.cache_budget import cache_publication
from k1link.simulation.ai_polygon.semantic_objects import is_rigid_marking, object_operation
from k1link.simulation.ai_polygon.semantic_vectors import vector_operation
from k1link.simulation.ai_polygon.urban_maps import validate_map
from k1link.simulation.ai_polygon.worlds import write_json
HASH = re.compile(r"[0-9a-f]{64}")
REQUEST = re.compile(r"[a-zA-Z0-9_-]{16,80}")
MAX_STATE = 8 * 1024**2
# A collection contains at most 256 bounded four-window shards. This is receipt
# metadata, not a relaxation of geometry or training admission.
MAX_OBSERVATION_WINDOWS = 256 * 4
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
).hexdigest()
def paths(feature):
geometry = feature["geometry"]
return geometry["coordinates"] if geometry["type"] == "Polygon" else [geometry["coordinates"]]
def _cross(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def _intersects(a, b, c, d):
if any(max(a[k], b[k]) < min(c[k], d[k]) or max(c[k], d[k]) < min(a[k], b[k]) for k in (0, 1)):
return False
return _cross(a, b, c) * _cross(a, b, d) <= 0 and _cross(c, d, a) * _cross(c, d, b) <= 0
def validate_path(points, closed):
if len(points) < (4 if closed else 2) or len(points) > 4096:
raise ValueError("Недопустимое число точек контура.")
if closed and points[0] != points[-1]:
raise ValueError("Контур должен быть замкнут.")
for point in points:
if len(point) != 3 or any(
type(v) not in (int, float) or not math.isfinite(v) or abs(v) > 1e6 for v in point
):
raise ValueError("Некорректные координаты.")
segments = list(zip(points, points[1:], strict=False))
if any(a[:2] == b[:2] for a, b in segments):
raise ValueError("Совпадающие точки контура.")
for a, b, c in zip(points, points[1:], points[2:], strict=False):
if _cross(a, b, c) == 0 and sum((a[k] - b[k]) * (c[k] - b[k]) for k in (0, 1)) > 0:
raise ValueError("Контур возвращается по собственному сегменту.")
for i, (a, b) in enumerate(segments):
for j in range(i + 2, len(segments)):
if closed and i == 0 and j == len(segments) - 1:
continue
c, d = segments[j]
# Plan editing is admitted only for the affected path; other objects
# and pre-existing geometry are not normalized or re-approximated.
if _intersects(a, b, c, d):
raise ValueError("Правка создаёт самопересечение контура в плане.")
if closed and sum(a[0] * b[1] - b[0] * a[1] for a, b in segments) == 0:
raise ValueError("Контур не имеет площади.")
def _inside(point, ring):
x, y = point[:2]
inside = False
for a, b in zip(ring, ring[1:], strict=False):
if (a[1] > y) != (b[1] > y) and x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0]:
inside = not inside
return inside
def validate_holes(rings):
for i, ring in enumerate(rings):
for other in rings[i + 1 :]:
if any(
_intersects(a, b, c, d)
for a, b in zip(ring, ring[1:], strict=False)
for c, d in zip(other, other[1:], strict=False)
):
raise ValueError("Границы полигона пересекаются.")
if i and (
not _inside(ring[0], rings[0])
or any(_inside(ring[0], hole) for j, hole in enumerate(rings[1:], 1) if i != j)
):
raise ValueError("Внутренняя граница должна оставаться внутри своей области.")
def apply_operations(document, operations, *, verified_history=False, origin="human-edit"):
if not isinstance(operations, list) or not 1 <= len(operations) <= 256:
raise ValueError("Сохраните от 1 до 256 действий за один раз.")
result = document if verified_history else copy.deepcopy(document)
changed = False
by_id = {f.get("id"): f for f in result["features"]}
for op in operations:
if not isinstance(op, dict):
raise ValueError("Некорректное действие.")
kind = op.get("kind")
if kind == "region":
validate_path(op.get("brush", []), True)
curved = (
isinstance(op.get("feature_id"), str)
and kind in ("move", "insert", "delete")
and bool(
by_id.get(op.get("feature_id"), {})
.get("properties", {})
.get("editor_curves", {})
.get(str(op.get("path")))
)
)
if (
kind
in (
"retemplate",
"place",
"transform",
"remove",
"curve",
"delete_vertices",
"region",
"translate",
"translate_vertices",
"duplicate_vertex",
"duplicate_marking",
)
or curved
):
handler = (
object_operation
if kind in ("place", "transform", "remove", "retemplate")
else vector_operation
)
updated = handler(result["features"], op, origin)
if updated is result["features"]:
continue
if not verified_history:
previous = {f["id"]: f for f in result["features"]}
for f in updated:
if (
previous.get(f["id"]) is f
or f["properties"].get("review_status") == "rejected"
):
continue
rings = paths(f)
for ring in rings:
validate_path(ring, f["geometry"]["type"] == "Polygon")
if f["geometry"]["type"] == "Polygon":
validate_holes(rings)
result["features"] = updated
by_id = {f["id"]: f for f in updated}
changed = True
continue
fields = {"kind", "feature_id", "path", "index"}
fields |= {"position"} if kind == "move" else {"t"} if kind == "insert" else set()
if kind not in ("move", "insert", "delete") or set(op) != fields:
raise ValueError("Неизвестное действие.")
feature = by_id.get(op["feature_id"]) if isinstance(op["feature_id"], str) else None
if not feature or feature["properties"].get("review_status") == "rejected":
raise ValueError("Выберите существующий видимый контур.")
if not verified_history and is_rigid_marking(feature):
raise ValueError("Элемент разметки перемещается целиком; вершины не редактируются.")
rings = paths(feature)
path, index = op["path"], op["index"]
if type(path) is not int or not 0 <= path < len(rings):
raise ValueError("Контур не найден.")
points = rings[path]
closed = feature["geometry"]["type"] == "Polygon"
count = len(points) - int(closed)
if type(index) is not int or not 0 <= index < count:
raise ValueError("Точка не найдена.")
if kind == "insert":
t = op["t"]
if index >= len(points) - 1 or type(t) not in (int, float) or not 0 < t < 1:
raise ValueError("Новая точка должна лежать внутри выбранного сегмента.")
a, b = points[index : index + 2]
points.insert(index + 1, [a[k] + t * (b[k] - a[k]) for k in range(3)])
elif kind == "move":
point = op["position"]
if (
not isinstance(point, list)
or len(point) != 3
or any(
type(v) not in (int, float) or not math.isfinite(v) or abs(v) > 1e6
for v in point
)
):
raise ValueError("Некорректные координаты.")
if point[2] != points[index][2]:
raise ValueError("Редактирование в плане сохраняет исходную высоту.")
if point == points[index]:
continue
points[index] = point[:]
else:
points.pop(index)
if closed:
points[-1] = points[0][:]
if not verified_history:
validate_path(points, closed)
if closed and len(rings) > 1 and not verified_history:
validate_holes(rings)
feature["properties"] = {
**feature["properties"],
"confidence": None,
"confidence_status": "not-assessed",
"review_status": "unreviewed",
"annotation_origin": origin,
}
changed = True
if not changed:
return result
# A human draft is not Gaussian-only inference or a training-ready truth.
result["schema_version"] = "missioncore.urban-edit/v1"
result["source"] = {k: v for k, v in result["source"].items() if k != "gaussian_only"}
return result
class SemanticEdits:
def __init__(self, data_dir, maps):
self.root = data_dir / "ai-polygon" / "semantic-edits"
self.maps = maps
def _path(self, world):
if not HASH.fullmatch(world["sha256"]):
raise ValueError("Некорректная версия сцены.")
return self.root / (world["sha256"] + ".json")
def _read(self, world):
path = self._path(world)
if not path.exists():
return {"schema_version": "missioncore.semantic-edits/v1", "revisions": []}
if path.is_symlink() or path.stat().st_size > MAX_STATE:
raise ValueError("Хранилище правок не прошло проверку.")
state = json.loads(path.read_text())
revisions = state["revisions"]
for i, row in enumerate(revisions):
payload = {k: v for k, v in row.items() if k != "revision"}
if digest(payload) != row["revision"] or row["parent"] != (
revisions[i - 1]["revision"] if i else None
):
raise ValueError("Нарушена целостность истории правок.")
return state
def _model(self, world, sha):
if not isinstance(sha, str) or not HASH.fullmatch(sha):
raise ValueError("Некорректная версия алгоритма.")
path = self.maps.directory(world) / (sha + ".json")
if path.is_symlink():
raise ValueError("Недопустимая ссылка на карту.")
document = json.loads(path.read_text())
if digest(document) != sha:
raise ValueError("Исходная карта изменилась.")
validate_map(document, world)
if document["schema_version"] == "missioncore.urban-map/v1":
raise ValueError("Для редактора нужна векторная карта инфраструктуры.")
return document
def _view(self, world, state):
revisions = state["revisions"]
latest = self.maps.get(world)
sha = revisions[0]["model_sha256"] if revisions else digest(latest)
model = self._model(world, sha)
edited = copy.deepcopy(model) if revisions else model
for row in revisions:
if row["model_sha256"] != sha:
raise ValueError("Изменилась основа ручной версии.")
edited = apply_operations(
edited,
row["operations"],
verified_history=True,
origin=row.get("origin", "human-edit"),
)
return self._response(state, model, edited, sha, digest(latest))
@staticmethod
def _response(state, model, edited, sha, latest_sha):
revisions = state["revisions"]
head = revisions[-1] if revisions else None
return {
"schema_version": "missioncore.semantic-editor/v1",
"model_sha256": sha,
"latest_model_sha256": latest_sha,
"revision": head["revision"] if head else None,
"model": model,
"edited": edited,
"history": [
{
"revision": r["revision"],
"created_at": r["created_at"],
"actions": len(r["operations"]),
}
for r in revisions
],
"learning": {
"state": "queued" if head else "no-edits",
**(state.get("deliveries", {}).get(head["revision"], {}) if head else {}),
"dataset_ready": False,
},
}
def get(self, world):
return self._view(world, self._read(world))
def export(self, world, revision):
"""Portable annotation metadata, explicitly not an image dataset."""
state = self._read(world)
index = next(
(i for i, row in enumerate(state["revisions"]) if row["revision"] == revision),
None,
)
if index is None:
raise FileNotFoundError("Ревизия не найдена.")
rows = state["revisions"][: index + 1]
view = self._view(world, {**state, "revisions": rows})
package = {
"schema_version": "missioncore.semantic-annotation-export/v1",
"world_sha256": world["sha256"],
"collider_sha256": world.get("collider_sha256"),
"model_sha256": view["model_sha256"],
"revision": revision,
"model": view["model"],
"edited": view["edited"],
"revisions": rows,
"review": {"state": "draft", "complete_regions": [], "dataset_ready": False},
}
return {"sha256": digest(package), "package": package}
def save(self, world, body):
if not isinstance(body, dict) or set(body) - {"origin"} != {
"expected_revision",
"model_sha256",
"request_id",
"operations",
}:
raise ValueError("Некорректный запрос сохранения.")
if not isinstance(body["request_id"], str) or not REQUEST.fullmatch(body["request_id"]):
raise ValueError("Некорректный идентификатор сохранения.")
if body.get("origin", "human-edit") not in ("human-edit", "agent-proposal"):
raise ValueError("Некорректное происхождение правки.")
request_hash = digest(body)
# Reserve a bounded complete atomic replacement. Shared lock handles
# concurrent tabs/processes; an idempotent replay needs no new capacity.
with cache_publication(self.root, 0, limit=64 * 1024**2):
state = self._read(world)
revisions = state["revisions"]
for row in revisions:
if row["request_id"] == body["request_id"]:
if row["request_sha256"] != request_hash:
raise RuntimeError(
"Идентификатор сохранения уже использован для другой правки."
)
return self._view(world, state)
head = revisions[-1]["revision"] if revisions else None
if body["expected_revision"] != head:
raise RuntimeError("Карта изменена в другом окне. Откройте сохранённую версию.")
if not revisions:
# Use the displayed immutable model even if a new analysis just
# published; never silently rebase a human operation by index.
model = self._model(world, body["model_sha256"])
view = self._response(
state, model, model, body["model_sha256"], digest(self.maps.get(world))
)
else:
view = self._view(world, state)
if body["model_sha256"] != view["model_sha256"]:
raise RuntimeError("Правки относятся к другой основе.")
edited = apply_operations(
view["edited"], body["operations"], origin=body.get("origin", "human-edit")
)
if edited == view["edited"]:
raise ValueError("Нет изменений для сохранения.")
row = {
**body,
"parent": head,
"created_at": datetime.now(UTC).isoformat(),
"request_sha256": request_hash,
}
row["revision"] = digest(row)
state["revisions"].append(row)
raw = json.dumps(state, ensure_ascii=False, allow_nan=False).encode()
if len(raw) > MAX_STATE:
raise ValueError(
"Лимит локальных семантических правок достигнут. История сохранена."
)
# Account for the temporary replacement while the common lock is held.
import shutil
from k1link.cache_budget import FREE_RESERVE, usage
if usage(self.root)[0] + len(raw) > 64 * 1024**2 or shutil.disk_usage(
self.root
).free < FREE_RESERVE + len(raw):
raise ValueError("Недостаточно места для сохранения правок.")
write_json(self._path(world), state)
# Return the exact admitted geometry. Replaying the entire history
# here duplicated work and could fail after a successful commit.
return self._response(
state, view["model"], edited, view["model_sha256"], view["latest_model_sha256"]
)
def pending(self, worlds):
"""The revision itself is the durable outbox: no dual-write window."""
rows = []
for world in worlds:
state = self._read(world)
for revision in state["revisions"]:
if revision["revision"] not in state.get("deliveries", {}):
rows.append(
{
"world_id": world["world_id"],
"world_sha256": world["sha256"],
"revision": revision["revision"],
"created_at": revision["created_at"],
}
)
return sorted(rows, key=lambda r: (r["created_at"], r["revision"]))[:20]
def receipt(self, world, revision, body):
allowed = {"state", "package_sha256", "dataset_sha256", "sample_count"}
if not isinstance(body, dict) or set(body) != allowed:
raise ValueError("Некорректная квитанция.")
order = {"received": 1, "building": 2, "draft-ready": 3, "failed": 3}
if body["state"] not in order or not HASH.fullmatch(str(body["package_sha256"])):
raise ValueError("Некорректное состояние доставки.")
ready = body["state"] == "draft-ready"
if (
type(body["sample_count"]) is not int
or not 0 <= body["sample_count"] <= MAX_OBSERVATION_WINDOWS
or (
ready
and (not body["sample_count"] or not HASH.fullmatch(str(body["dataset_sha256"])))
)
or (not ready and (body["dataset_sha256"] is not None or body["sample_count"] != 0))
):
raise ValueError("Некорректный результат подготовки.")
with cache_publication(self.root, 0, limit=64 * 1024**2):
package = self.export(world, revision)
if body["package_sha256"] != package["sha256"]:
raise ValueError("Квитанция относится к другой аннотации.")
state = self._read(world)
deliveries = state.setdefault("deliveries", {})
previous = deliveries.get(revision)
if previous:
if previous == body or order[previous["state"]] > order[body["state"]]:
return previous
if order[previous["state"]] == 3:
raise RuntimeError("Завершённая квитанция неизменна.")
deliveries[revision] = body
raw = json.dumps(state, ensure_ascii=False, allow_nan=False).encode()
import shutil
from k1link.cache_budget import FREE_RESERVE, usage
if (
len(raw) > MAX_STATE
or usage(self.root)[0] + len(raw) > 64 * 1024**2
or shutil.disk_usage(self.root).free < FREE_RESERVE + len(raw)
):
raise ValueError("Недостаточно места для квитанции.")
write_json(self._path(world), state)
return body
@@ -0,0 +1,230 @@
"""Rigid marking operations shared by Core and the portable Worker builder."""
import copy
import json
import math
import re
from pathlib import Path
def catalog():
local = Path(__file__).with_name("marking-templates.json")
return json.loads(local.read_text())
def paths(f):
g = f["geometry"]
return g["coordinates"] if g["type"] == "Polygon" else [g["coordinates"]]
def is_rigid_marking(f):
p = f["properties"]
return p["class"] in ("road_marking", "crosswalk_marking") and not (
p["class"] == "road_marking"
and p.get("subtype") == "linear_marking"
and p.get("template_id") in (None, "", "linear_marking")
and not p.get("semantic_element_id")
)
def members(features, feature_id):
selected = next((f for f in features if f["id"] == feature_id), None)
if not selected or selected["properties"].get("review_status") == "rejected":
raise ValueError("Выберите существующий элемент.")
group = selected["properties"].get("semantic_element_id")
return (
[f for f in features if f["properties"].get("semantic_element_id") == group]
if group
else [selected]
)
def pivot(features):
points = [p for f in features for ring in paths(f) for p in ring]
return [(min(p[k] for p in points) + max(p[k] for p in points)) / 2 for k in range(3)]
def numbers(value, count):
return (
isinstance(value, list)
and len(value) == count
and all(type(v) in (int, float) and math.isfinite(v) and abs(v) <= 1e6 for v in value)
)
def object_operation(features, op, origin="human-edit"):
"""New list, unchanged objects retained; no-op returns the same list."""
kind = op.get("kind")
if kind == "retemplate":
if set(op) != {"kind", "feature_id", "template_id", "frame"}:
raise ValueError("Некорректная замена шаблона.")
chosen = members(features, op["feature_id"])
template = next((t for t in catalog()["templates"] if t["id"] == op["template_id"]), None)
frame = op["frame"]
if (
len(chosen) != 1
or chosen[0]["properties"]["class"] != "road_marking"
or not template
or len(template["polygons"]) != 1
or not isinstance(frame, list)
or len(frame) != 3
or not all(numbers(v, 3) for v in frame)
):
raise ValueError("Замена требует одного элемента и плоскости шаблона.")
origin_point, along, across = frame
lengths = [math.hypot(*v[:2]) for v in (along, across)]
if (
any(not 0.01 <= n <= 100 for n in lengths)
or abs(sum(along[k] * across[k] for k in (0, 1))) > 1e-8 * lengths[0] * lengths[1]
or along[0] * across[1] - along[1] * across[0] <= 0
or any(abs(v[2]) > n for v, n in zip((along, across), lengths, strict=True))
):
raise ValueError("Некорректные оси шаблона.")
q = copy.deepcopy(chosen[0])
q["geometry"] = dict(
type="Polygon",
coordinates=[
[
[origin_point[k] + p[0] * along[k] + p[1] * across[k] for k in range(3)]
for p in ring
]
for ring in template["polygons"][0]
],
)
q["properties"].pop("editor_curves", None)
q["properties"].update(
template_id=template["id"],
template_source=template["source"],
template_frame=frame,
height_source="existing-surface-plane-unverified",
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
annotation_origin=origin,
authority="observation-only",
route_permission="unassigned",
)
return [q if f is chosen[0] else f for f in features]
if kind == "place":
if (
set(op) != {"kind", "feature_id", "template_id", "position", "surface"}
or op["surface"] != "gaussian-visual"
):
raise ValueError("Некорректное размещение.")
if not isinstance(op["feature_id"], str) or not re.fullmatch(
r"user-[a-zA-Z0-9-]{16,64}", op["feature_id"]
):
raise ValueError("Некорректный идентификатор элемента.")
if not numbers(op["position"], 3):
raise ValueError("Некорректная точка поверхности.")
template = next((t for t in catalog()["templates"] if t["id"] == op["template_id"]), None)
if not template:
raise ValueError("Неизвестный шаблон.")
new_ids = {
op["feature_id"] if i == 0 else f"{op['feature_id']}-{i}"
for i in range(len(template["polygons"]))
}
if any(
f["id"] in new_ids or f["properties"].get("semantic_element_id") == op["feature_id"]
for f in features
):
raise ValueError("Элемент уже существует.")
result = features[:]
for i, polygon in enumerate(template["polygons"]):
result.append(
dict(
id=op["feature_id"] if i == 0 else f"{op['feature_id']}-{i}",
geometry=dict(
type="Polygon",
coordinates=[
[
[
p[0] + op["position"][0],
p[1] + op["position"][1],
op["position"][2],
]
for p in ring
]
for ring in polygon
],
),
properties=dict(
**{"class": "road_marking"},
authority="observation-only",
route_permission="unassigned",
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
annotation_origin=origin,
**(
{"subtype": "linear_marking"}
if template["id"] == "linear_marking"
else {"semantic_element_id": op["feature_id"]}
),
template_id=template["id"],
template_source=template["source"],
height_source="gaussian-visual-pick-unverified",
),
)
)
return result
expected = (
{"kind", "feature_id", "delta", "angle"} if kind == "transform" else {"kind", "feature_id"}
)
if kind not in ("transform", "remove") or set(op) != expected:
raise ValueError("Неизвестное действие элемента.")
chosen = members(features, op["feature_id"])
if any(f["properties"]["class"] not in ("road_marking", "crosswalk_marking") for f in chosen):
raise ValueError("Действие предназначено для элемента разметки.")
if kind == "transform":
if (
not numbers(op["delta"], 2)
or type(op["angle"]) not in (int, float)
or not math.isfinite(op["angle"])
or abs(op["angle"]) > math.pi * 2
):
raise ValueError("Некорректное перемещение элемента.")
if op["delta"] == [0, 0] and op["angle"] == 0:
return features
ids = {f["id"] for f in chosen}
centre = pivot(chosen)
result = []
for f in features:
if f["id"] not in ids:
result.append(f)
continue
q = copy.deepcopy(f)
q["properties"].update(
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
annotation_origin=origin,
)
if kind == "remove":
q["properties"]["review_status"] = "rejected"
else:
c, s = math.cos(op["angle"]), math.sin(op["angle"])
for ring in paths(q):
for p in ring:
x, y = p[:2]
# Translation never subtracts/re-adds a pivot; retain no-op axes exactly.
if op["angle"]:
x, y = (
centre[0] + c * (x - centre[0]) - s * (y - centre[1]),
centre[1] + s * (x - centre[0]) + c * (y - centre[1]),
)
p[0], p[1] = x + op["delta"][0], y + op["delta"][1]
for nodes in q["properties"].get("editor_curves", {}).values():
for node in nodes:
x, y = node["point"][:2]
if op["angle"]:
x, y = (
centre[0] + c * (x - centre[0]) - s * (y - centre[1]),
centre[1] + s * (x - centre[0]) + c * (y - centre[1]),
)
for key in ("incoming", "outgoing"):
a, b = node[key]
node[key] = [c * a - s * b, s * a + c * b]
node["point"][:2] = [x + op["delta"][0], y + op["delta"][1]]
result.append(q)
return result
@@ -0,0 +1,387 @@
"""Portable vector editing. Geometry checks remain at Core's admission boundary."""
import copy
import re
try:
from .semantic_objects import is_rigid_marking, members, numbers, paths
except ImportError:
from semantic_objects import is_rigid_marking, members, numbers, paths
def knots(f, path):
saved = f["properties"].get("editor_curves", {}).get(str(path))
if saved is not None:
return copy.deepcopy(saved)
points = paths(f)[path]
if f["geometry"]["type"] == "Polygon":
points = points[:-1]
return [dict(point=p[:], incoming=[0, 0], outgoing=[0, 0]) for p in points]
def curve_point(a, b, t):
u = 1 - t
return [
u * u * u * a["point"][k]
+ 3 * u * u * t * (a["point"][k] + a["outgoing"][k])
+ 3 * u * t * t * (b["point"][k] + b["incoming"][k])
+ t * t * t * b["point"][k]
for k in (0, 1)
] + [a["point"][2] + t * (b["point"][2] - a["point"][2])]
def with_knots(f, path, nodes):
closed = f["geometry"]["type"] == "Polygon"
if not (3 if closed else 2) <= len(nodes) <= 4095:
raise ValueError("В контуре недостаточно точек. Выберите весь контур для удаления.")
curve = []
for i in range(len(nodes) - int(not closed)):
a, b = nodes[i], nodes[(i + 1) % len(nodes)]
curve.append(a["point"][:])
if any(a["outgoing"]) or any(b["incoming"]):
curve.extend(curve_point(a, b, j / 16) for j in range(1, 16))
curve.append(nodes[0 if closed else -1]["point"][:])
q = copy.deepcopy(f)
q["properties"].setdefault("editor_curves", {})[str(path)] = nodes
if closed:
q["geometry"]["coordinates"][path] = curve
else:
q["geometry"]["coordinates"] = curve
return q
def insert_knot(nodes, i, t, closed):
j = (i + 1) % len(nodes)
if not closed and j == 0 or type(t) not in (int, float) or not 0 < t < 1:
raise ValueError("Выберите середину сегмента.")
a, b = nodes[i], nodes[j]
def mix(x, y):
return [v + t * (y[k] - v) for k, v in enumerate(x)]
def sub(x, y):
return [v - y[k] for k, v in enumerate(x)]
A, D = a["point"][:2], b["point"][:2]
B = [v + a["outgoing"][k] for k, v in enumerate(A)]
C = [v + b["incoming"][k] for k, v in enumerate(D)]
ab, bc, cd = mix(A, B), mix(B, C), mix(C, D)
abc, bcd = mix(ab, bc), mix(bc, cd)
point = mix(abc, bcd)
a["outgoing"], b["incoming"] = sub(ab, A), sub(cd, D)
nodes.insert(
i + 1,
dict(
point=point + [a["point"][2] + t * (b["point"][2] - a["point"][2])],
incoming=sub(abc, point),
outgoing=sub(bcd, point),
),
)
def contour(features, fid):
selected = members(features, fid)
if len(selected) != 1 or is_rigid_marking(selected[0]):
raise ValueError("Разметка редактируется целиком.")
return selected[0]
def validate_index(f, op):
p, i = op.get("path"), op.get("index")
rings = paths(f)
if type(p) is not int or not 0 <= p < len(rings):
raise ValueError("Контур не найден.")
saved = f["properties"].get("editor_curves", {}).get(str(p))
count = (
len(saved) if saved is not None
else len(rings[p]) - int(f["geometry"]["type"] == "Polygon")
)
if type(i) is not int or not 0 <= i < count:
raise ValueError("Точка не найдена.")
def index_nodes(f, op):
validate_index(f, op)
return knots(f, op["path"])
def duplicate_vertex(features, op, origin):
if (
set(op) - {"side"} != {"kind", "feature_id", "path", "index", "delta", "axis"}
or ("side" in op and op["side"] not in ("before", "after"))
or op["axis"] not in ("x", "y", "z", "xy", "xz", "yz")
or not numbers(op["delta"], 3)
or any(v and "xyz"[k] not in op["axis"] for k, v in enumerate(op["delta"]))
):
raise ValueError("Некорректное перемещение по осям.")
f = contour(features, op["feature_id"])
nodes = index_nodes(f, op)
if op["delta"] == [0, 0, 0]:
return features
if not any(op["delta"][:2]):
raise ValueError(
"Продолжение контура должно иметь длину в плане: используйте X, Y или плоскость."
)
node = copy.deepcopy(nodes[op["index"]])
node["point"] = [
v + op["delta"][k] if op["delta"][k] else v for k, v in enumerate(node["point"])
]
# Old revisions keep their original order. New gestures explicitly record
# the chosen arm so preview, persistence and Worker replay cannot disagree.
index = (
op["index"] + int(op["side"] == "after")
if "side" in op
else 0
if f["geometry"]["type"] == "LineString" and op["index"] == 0
else op["index"] + 1
)
nodes.insert(index, node)
q = with_knots(f, op["path"], nodes)
q["properties"].pop("height_projection", None)
q["properties"].update(
annotation_origin=origin,
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
height_source="human-vertex-extension-unverified",
)
return [q if v is f else v for v in features]
def duplicate_marking(features, op, origin):
if (
set(op) != {"kind", "feature_id", "new_feature_id", "delta", "axis"}
or not isinstance(op["new_feature_id"], str)
or not re.fullmatch(r"user-[a-zA-Z0-9-]{16,64}", op["new_feature_id"])
):
raise ValueError("Некорректное копирование элемента.")
chosen = members(features, op["feature_id"])
if any(f["properties"]["class"] not in ("road_marking", "crosswalk_marking") for f in chosen):
raise ValueError("Выберите элемент разметки.")
moved = vector_operation(
chosen,
dict(
kind="translate",
feature_id=op["feature_id"],
vertices=[],
delta=op["delta"],
axis=op["axis"],
),
origin,
)
if moved is chosen:
return features
copies = copy.deepcopy(moved)
for i, q in enumerate(copies):
q["id"] = op["new_feature_id"] if i == 0 else f"{op['new_feature_id']}-{i}"
if q["properties"].get("semantic_element_id"):
q["properties"]["semantic_element_id"] = op["new_feature_id"]
q["properties"].pop("height_projection", None)
q["properties"]["height_source"] = "human-copy-unverified"
ids = {q["id"] for q in copies}
if any(
f["id"] in ids or f["properties"].get("semantic_element_id") == op["new_feature_id"]
for f in features
):
raise ValueError("Элемент уже существует.")
return features + copies
def vector_operation(features, op, origin="human-edit"):
kind = op["kind"]
updated = {}
if kind == "duplicate_marking":
return duplicate_marking(features, op, origin)
if kind == "duplicate_vertex":
return duplicate_vertex(features, op, origin)
if kind in ("translate", "translate_vertices"):
if (
set(op) != {"kind", "feature_id", "vertices", "delta", "axis"}
or op["axis"] not in ("x", "y", "z", "xy", "xz", "yz")
or not numbers(op["delta"], 3)
or any(v and "xyz"[k] not in op["axis"] for k, v in enumerate(op["delta"]))
):
raise ValueError("Некорректное перемещение по осям.")
if op["delta"] == [0, 0, 0]:
return features
selected = members(features, op["feature_id"])
if kind == "translate" and selected[0]["properties"]["class"] in (
"road_marking",
"crosswalk_marking",
):
for f in selected:
q = copy.deepcopy(f)
for ring in paths(q):
for point in ring:
for k in range(3):
point[k] += op["delta"][k]
for nodes in q["properties"].get("editor_curves", {}).values():
for node in nodes:
node["point"] = [v + op["delta"][k] for k, v in enumerate(node["point"])]
updated[f["id"]] = q
else:
if not isinstance(op["vertices"], list) or not 1 <= len(op["vertices"]) <= 4096:
raise ValueError("Некорректное выделение.")
groups = {}
for v in op["vertices"]:
if set(v) != {"feature_id", "path", "index"}:
raise ValueError("Некорректная точка.")
f = contour(features, v["feature_id"])
validate_index(f, v)
groups.setdefault(f["id"], {}).setdefault(v["path"], set()).add(v["index"])
for fid, chosen in groups.items():
q = contour(features, fid)
for p, indices in chosen.items():
nodes = knots(q, p)
for i in indices:
nodes[i]["point"] = [
v + op["delta"][k] for k, v in enumerate(nodes[i]["point"])
]
q = with_knots(q, p, nodes)
updated[fid] = q
if op["delta"][2]:
for q in updated.values():
q["properties"].pop("height_projection", None)
q["properties"]["height_source"] = "human-axis-edit-unverified"
elif kind == "delete_vertices":
if (
set(op) != {"kind", "vertices"}
or not isinstance(op["vertices"], list)
or not 1 <= len(op["vertices"]) <= 4096
):
raise ValueError("Некорректное выделение.")
groups = {}
for v in op["vertices"]:
if set(v) != {"feature_id", "path", "index"}:
raise ValueError("Некорректное выделение.")
f = contour(features, v["feature_id"])
validate_index(f, v)
groups.setdefault(f["id"], {}).setdefault(v["path"], set()).add(v["index"])
for fid, chosen in groups.items():
f = contour(features, fid)
all_selected = all(
len(chosen.get(p, set())) == len(knots(f, p)) for p in range(len(paths(f)))
)
if all_selected:
q = copy.deepcopy(f)
q["properties"]["review_status"] = "rejected"
else:
q = f
for p, indices in chosen.items():
q = with_knots(q, p, [k for i, k in enumerate(knots(f, p)) if i not in indices])
updated[fid] = q
elif kind == "region":
if (
set(op) != {"kind", "feature_id", "token", "mode", "brush", "polygons"}
or op["mode"] not in ("union", "difference")
or not isinstance(op["token"], str)
or not re.fullmatch(r"[a-zA-Z0-9-]{16,64}", op["token"])
):
raise ValueError("Некорректная область.")
previous = next((f for f in features if f["id"] == op["feature_id"]), None)
if previous and (
previous["properties"]["class"] not in ("pedestrian_area", "sidewalk")
or previous["properties"].get("review_status") == "rejected"
):
raise ValueError("Выберите пешеходную область.")
if not previous and (
op["mode"] != "union" or not re.fullmatch(r"user-[a-zA-Z0-9-]{16,64}", op["feature_id"])
):
raise ValueError("Неизвестная область.")
brush = op["brush"]
if (
not isinstance(brush, list)
or not 4 <= len(brush) <= 129
or brush[0] != brush[-1]
or not all(numbers(p, 3) for p in brush)
):
raise ValueError("Некорректный контур пера.")
polygons = op["polygons"]
if (
not isinstance(polygons, list)
or len(polygons) > 64
or not polygons
and op["mode"] != "difference"
):
raise ValueError("Некорректный результат области.")
props = (
copy.deepcopy(previous["properties"])
if previous
else dict(
**{"class": "pedestrian_area"},
authority="observation-only",
route_permission="unassigned",
)
)
props.pop("editor_curves", None)
props.update(
annotation_origin=origin,
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
height_source="human-region-unverified",
region_origin_id=op["feature_id"],
)
result = [f for f in features if f is not previous]
for i, polygon in enumerate(polygons):
fid = op["feature_id"] if i == 0 else f"{op['feature_id']}-{op['token']}-{i}"
if any(f["id"] == fid for f in result) or not isinstance(polygon, list) or not polygon:
raise ValueError("Некорректный идентификатор или полигон.")
result.append(
dict(
id=fid,
properties=copy.deepcopy(props),
geometry=dict(type="Polygon", coordinates=copy.deepcopy(polygon)),
)
)
if not polygons and previous:
q = copy.deepcopy(previous)
q["properties"].update(props, review_status="rejected")
result.append(q)
return result
else:
fields = {"kind", "feature_id", "path", "index"}
fields |= (
{"position"}
if kind == "move"
else {"t"}
if kind == "insert"
else {"incoming", "outgoing"}
if kind == "curve"
else set()
)
if kind not in ("move", "insert", "delete", "curve") or set(op) != fields:
raise ValueError("Некорректная векторная операция.")
f = contour(features, op["feature_id"])
nodes = index_nodes(f, op)
i = op["index"]
if kind == "curve":
if (
set(op) != {"kind", "feature_id", "path", "index", "incoming", "outgoing"}
or not numbers(op["incoming"], 2)
or not numbers(op["outgoing"], 2)
):
raise ValueError("Некорректные ручки кривой.")
if nodes[i]["incoming"] == op["incoming"] and nodes[i]["outgoing"] == op["outgoing"]:
return features
nodes[i].update(incoming=op["incoming"][:], outgoing=op["outgoing"][:])
elif kind == "move":
if not numbers(op["position"], 3) or op["position"][2] != nodes[i]["point"][2]:
raise ValueError("Редактирование в плане сохраняет высоту.")
nodes[i]["point"] = op["position"][:]
elif kind == "insert":
insert_knot(nodes, i, op["t"], f["geometry"]["type"] == "Polygon")
elif kind == "delete":
nodes.pop(i)
else:
raise ValueError("Неизвестная векторная операция.")
updated[f["id"]] = with_knots(f, op["path"], nodes)
for q in updated.values():
rejected = q["properties"].get("review_status") == "rejected"
q["properties"].update(
annotation_origin=origin,
confidence=None,
confidence_status="not-assessed",
review_status="rejected" if rejected else "unreviewed",
)
return [updated.get(f["id"], f) for f in features]
+17 -3
View File
@@ -9,6 +9,9 @@ from pathlib import Path
from k1link.simulation.ai_polygon.worlds import write_json
CLASSES = {
"road_boundary",
"pedestrian_boundary",
"building_facade",
"curb",
"bike_lane",
"crosswalk_area",
@@ -28,7 +31,7 @@ def validate_map(document: dict, world: dict) -> dict:
raise ValueError("Infrastructure map must be an object")
if (
document.get("schema_version")
not in {"missioncore.urban-map/v1", "missioncore.urban-map/v2"}
not in {"missioncore.urban-map/v1", "missioncore.urban-map/v2", "missioncore.urban-map/v3"}
or document.get("type") != "FeatureCollection"
):
raise ValueError("Unsupported infrastructure map")
@@ -46,6 +49,11 @@ def validate_map(document: dict, world: dict) -> dict:
"collider_sha256"
):
raise ValueError("Infrastructure map belongs to a different scene revision")
if document["schema_version"] == "missioncore.urban-map/v3":
if source.get("gaussian_only") is not True or not re.fullmatch(
"[0-9a-f]{64}", str(source.get("artifact_sha256", ""))
):
raise ValueError("Missing Gaussian derivation identity")
coverage = document.get("coverage")
if not isinstance(coverage, dict):
raise ValueError("Missing infrastructure coverage")
@@ -72,7 +80,7 @@ def validate_map(document: dict, world: dict) -> dict:
or prop.get("route_permission") != "unassigned"
):
raise ValueError("Infrastructure observations cannot grant route permissions")
vector = document["schema_version"] == "missioncore.urban-map/v2"
vector = document["schema_version"] in {"missioncore.urban-map/v2", "missioncore.urban-map/v3"}
if vector:
identifier = feature.get("id")
score = prop.get("confidence")
@@ -83,7 +91,13 @@ def validate_map(document: dict, world: dict) -> dict:
):
raise ValueError("Invalid or duplicate infrastructure identity")
identifiers.add(identifier)
if type(score) not in (int, float) or not math.isfinite(score) or not 0 <= score <= 1:
unassessed = (
document["schema_version"] == "missioncore.urban-map/v3"
and score is None
and prop.get("confidence_status") == "not-assessed"
)
measured = type(score) in (int, float) and math.isfinite(score) and 0 <= score <= 1
if not (unassessed or measured):
raise ValueError("Invalid infrastructure confidence")
if prop.get("review_status") not in {"unreviewed", "accepted", "rejected"}:
raise ValueError("Invalid infrastructure review state")
@@ -0,0 +1,31 @@
"""Location labels and reversible removal without changing scan identity."""
from .library import LibraryMetadata
class WorldLibrary:
def __init__(self, worlds):
self.worlds = worlds
self.metadata = LibraryMetadata(worlds.root.parent / "world-library")
def present(self, row):
metadata = self.metadata.get(row["world_id"])
return {**row, **metadata, "name": metadata.get("display_name", row["name"])}
def get(self, world_id):
return self.present(self.worlds.get(world_id))
def list(self):
return [self.present(row) for row in self.worlds.list()]
def update(self, world_id, changes):
with self.worlds.lock:
self.worlds.get(world_id) # Never create metadata for an unknown scan.
self.metadata.update(world_id, changes)
return self.get(world_id)
def require_visible(self, world_id):
row = self.get(world_id)
if row.get("removed"):
raise RuntimeError("Локация удалена из списка. Сначала восстановите её.")
return row
+33 -4
View File
@@ -28,6 +28,7 @@ from k1link.simulation.ai_polygon.contracts import (
WorkerResult,
WorkerWorldCreate,
WorldCreate,
WorldLibraryUpdate,
WorldSettings,
)
from k1link.simulation.ai_polygon.editor_cache import EditorCache
@@ -36,6 +37,7 @@ from k1link.web.route_preparation_api import build_route_preparation_router, pub
from k1link.simulation.ai_polygon.robots import robot_catalog, select_robot
from k1link.simulation.ai_polygon.runs import RunStore
from k1link.simulation.ai_polygon.worlds import CHUNK_BYTES, SOURCES, WorldStore
from k1link.simulation.ai_polygon.world_library import WorldLibrary
def build_ai_polygon_router(
@@ -43,6 +45,7 @@ def build_ai_polygon_router(
) -> APIRouter:
worlds = WorldStore(data_dir)
runs = RunStore(worlds, queue)
world_library = WorldLibrary(worlds)
editor = EditorCache(data_dir, worlds)
routes = RoutePreparationStore(data_dir)
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
@@ -73,6 +76,12 @@ def build_ai_polygon_router(
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
urban_maps = UrbanMapStore(data_dir)
from k1link.web.semantic_edits_api import build_semantic_edits_router
router.include_router(build_semantic_edits_router(data_dir, worlds, urban_maps, invoke, authenticate))
from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs
from k1link.web.infrastructure_api import build_infrastructure_router
infrastructure = InfrastructureJobs(data_dir)
router.include_router(build_infrastructure_router(infrastructure, urban_maps, worlds, runs, invoke, authenticate))
@router.get("/worlds/{world_id}/urban-map")
def urban_map(world_id: str):
@@ -99,7 +108,8 @@ def build_ai_polygon_router(
def catalog():
runtime = runs.status()
runtime = {**runtime, "active_run": public_run(runtime.get("active_run"))}
locations = worlds.list()
all_locations = world_library.list()
locations = [w for w in all_locations if not w.get("removed")]
if "project-sog" not in (runtime.get("worker") or {}).get("scene_formats", []):
locations = [
{
@@ -116,6 +126,7 @@ def build_ai_polygon_router(
"sources": SOURCES,
"robots": robot_catalog(adapters),
"worlds": locations,
"removed_worlds": [w for w in all_locations if w.get("removed")],
"runtime": runtime,
"runs": [public_run(r) for r in runs.library.visible(runs.list(), "run_id")[:30]],
"plans": [public_plan(p) for p in runs.plans.visible_list()],
@@ -135,7 +146,16 @@ def build_ai_polygon_router(
@router.get("/worlds/{world_id}")
def get_world(world_id: str):
return invoke(worlds.get, world_id)
return invoke(world_library.get, world_id)
@router.patch("/worlds/{world_id}")
def update_world(world_id: str, body: WorldLibraryUpdate):
with runs.lock:
if body.removed and runs.active:
active = invoke(runs.get, runs.active)
if active["world"]["world_id"] == world_id:
raise HTTPException(409, "Сначала завершите симуляцию этой локации.")
return invoke(world_library.update, world_id, body.model_dump(exclude_none=True))
@router.get("/worlds/{world_id}/upload-prefix")
def upload_prefix(world_id: str):
@@ -229,8 +249,8 @@ def build_ai_polygon_router(
@router.post("/runs", status_code=201)
def start(body: RunCreate, idempotency_key: str = Header(alias="Idempotency-Key")):
if editor.pending() or routes.pending():
raise HTTPException(409, "Дождитесь подготовки сцены и маршрута.")
if editor.pending() or routes.pending() or infrastructure.pending():
raise HTTPException(409, "Дождитесь завершения подготовки сцены, маршрута или анализа инфраструктуры.")
if body.clock == "realtime":
graph = invoke(compose, adapters, body.composition)
body = body.model_copy(update={"composition": graph.selection_document()})
@@ -361,6 +381,15 @@ def build_ai_polygon_router(
except RuntimeError:
return value
return {"action": "route-preparation", "preparation": claimed}
if value["action"] == "idle" and runs.queue is not None:
worker = runs.status().get("worker") or {}
try:
claimed = infrastructure.dispatch(body.instance_id, runs.queue,
worker.get("infrastructure_provider_sha256"))
except RuntimeError:
return value
if claimed:
return {"action":"infrastructure-analysis", "analysis":claimed}
return value
@router.post("/worker/editor-cache/{key}")
+130
View File
@@ -0,0 +1,130 @@
"""Whole-location analysis commands and bounded Worker publication."""
import json
from fastapi import APIRouter, Header, HTTPException, Request
from fastapi.responses import FileResponse
from pydantic import BaseModel, ConfigDict
from k1link.simulation.ai_polygon.infrastructure_jobs import provider_identity
from k1link.simulation.ai_polygon.urban_maps import validate_map
class AnalysisRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
force: bool = False
request_id: str | None = None
def build_infrastructure_router(jobs, maps, worlds, runs, invoke, authenticate):
router = APIRouter()
@router.get("/worlds/{world_id}/infrastructure-analysis")
def status(world_id: str):
world = invoke(worlds.get, world_id)
return jobs.present(invoke(jobs.current, world))
@router.get("/infrastructure-analysis/queue")
def queue_status():
return {
"jobs": [
dict(
jobs.present(row),
world_id=row["world"]["world_id"],
name=row["world"].get("name", "Локация"),
)
for row in jobs.queue_rows()
]
}
@router.post("/worlds/{world_id}/infrastructure-analysis/{key}/cancel")
def cancel(world_id: str, key: str):
with runs.lock:
row = invoke(jobs.get, key)
if row["world"]["world_id"] != world_id:
raise HTTPException(404, "Расчёт не найден.")
return jobs.present(invoke(jobs.cancel, key))
@router.get("/worker/worlds/{world_id}/infrastructure-source")
def source(world_id: str, authorization: str | None = Header(default=None)):
authenticate(authorization)
world = invoke(worlds.get, world_id)
if not world.get("local_scene") or world.get("storage", {}).get("kind") != "project":
raise HTTPException(400, "Для анализа нужен исходный Gaussian-проект.")
return invoke(worlds.projects.analysis_package, world)
@router.get("/worker/worlds/{world_id}/infrastructure-archive")
def archive(world_id: str, authorization: str | None = Header(default=None)):
authenticate(authorization)
world = invoke(worlds.get, world_id)
if world.get("storage", {}).get("kind") != "project":
raise HTTPException(400, "Для анализа нужен исходный Gaussian-проект.")
path, descriptor = invoke(worlds.projects.analysis_archive, world)
return FileResponse(
path,
media_type="application/octet-stream",
headers={"ETag": '"' + descriptor["sha256"] + '"'},
)
@router.post("/worlds/{world_id}/infrastructure-analysis", status_code=202)
def start(world_id: str, body: AnalysisRequest | None = None):
with runs.lock:
worker = runs.status().get("worker") or {}
if worker.get("infrastructure_provider_sha256") != provider_identity():
raise HTTPException(409, "Подключите Worker с модулем анализа инфраструктуры.")
return jobs.present(
invoke(
jobs.request,
invoke(worlds.get, world_id),
bool(body and body.force),
body.request_id if body else None,
)
)
@router.post("/worker/infrastructure-analysis/{key}")
async def update(
key: str,
request: Request,
authorization: str | None = Header(default=None),
instance_id: str = Header(alias="Worker-Instance"),
):
authenticate(authorization)
invoke(runs.heartbeat, instance_id)
raw = bytearray()
async for part in request.stream():
raw.extend(part)
if len(raw) > 12 * 1024**2:
raise HTTPException(413, "Analysis result exceeds transport budget")
try:
body = json.loads(raw)
if not isinstance(body, dict):
raise ValueError("Analysis update must be an object")
with jobs.lock:
row = invoke(jobs.get, key)
if body.get("action") == "complete":
if row["status"] not in ("running", "ready") or row["owner"] != instance_id:
raise RuntimeError("Analysis is not owned by this worker")
if row.get("cancel_requested"):
raise RuntimeError("Analysis cancellation requested")
world = worlds.get(row["world"]["world_id"])
doc = validate_map(body["map"], world)
analysis = doc.get("analysis", {})
if analysis.get("job_key") != key or analysis.get("scope") != "whole-scene":
raise ValueError("Analysis result identity mismatch")
if analysis.get("provider_sha256") != row["identity"]["provider_sha256"]:
raise ValueError("Analysis provider changed")
if row["status"] == "ready":
if maps.get(world) != doc:
raise ValueError("Completed analysis result changed")
return jobs.present(row)
body["result"] = maps.save(world, doc)
value = jobs.update(key, body, instance_id)
if body.get("action") == "release" and runs.queue is not None:
runs.queue.release_simulation("aicache-" + key)
return jobs.present(value)
except (ValueError, KeyError, TypeError) as exc:
raise HTTPException(400, "Invalid infrastructure analysis update") from exc
except RuntimeError as exc:
raise HTTPException(409, str(exc)) from exc
return router
+84
View File
@@ -0,0 +1,84 @@
"""Operator metadata only; training media never enters this API."""
import json
from fastapi import APIRouter, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from k1link.simulation.ai_polygon.semantic_edits import MAX_STATE, SemanticEdits
from k1link.simulation.ai_polygon.semantic_objects import catalog
def build_semantic_edits_router(data_dir, worlds, maps, invoke, authenticate):
router = APIRouter()
store = SemanticEdits(data_dir, maps)
@router.get("/semantic-edits/templates")
def templates():
return catalog()
@router.get("/worlds/{world_id}/semantic-edits")
def get(world_id: str):
return invoke(store.get, invoke(worlds.get, world_id))
@router.post("/worlds/{world_id}/semantic-edits")
async def save(world_id: str, request: Request):
raw = bytearray()
async for chunk in request.stream():
# Group edits carry vertex references: action count is not byte size.
# Admit up to the existing durable metadata budget; store.save still
# checks geometry, action count, history capacity and atomicity.
if len(raw) + len(chunk) > MAX_STATE:
raise HTTPException(
413, "Размер запроса правок превышает 8 МиБ. Черновик не изменён."
)
raw.extend(chunk)
try:
body = json.loads(raw)
except (ValueError, UnicodeDecodeError) as exc:
raise HTTPException(400, "Некорректная правка.") from exc
# File locks, geometry admission and durable I/O must not block the
# event loop that serves the operator's other requests.
return await run_in_threadpool(
lambda: invoke(store.save, invoke(worlds.get, world_id), body)
)
@router.get("/worker/worlds/{world_id}/semantic-edits/{revision}")
def export(world_id: str, revision: str, request: Request):
authenticate(request.headers.get("authorization"))
return invoke(store.export, invoke(worlds.get, world_id), revision)
@router.get("/worker/semantic-edits/pending")
def pending(request: Request):
authenticate(request.headers.get("authorization"))
return {"jobs": invoke(store.pending, invoke(worlds.list))}
@router.get("/worlds/{world_id}/semantic-edits/status")
def status(world_id: str):
world = invoke(worlds.get, world_id)
state = invoke(store._read, world)
head = state["revisions"][-1]["revision"] if state["revisions"] else None
return {
"revision": head,
"state": "queued" if head else "no-edits",
**state.get("deliveries", {}).get(head, {}),
"training_eligible": False,
}
@router.post("/worker/worlds/{world_id}/semantic-edits/{revision}/receipt")
async def receipt(world_id: str, revision: str, request: Request):
authenticate(request.headers.get("authorization"))
raw = bytearray()
async for chunk in request.stream():
raw.extend(chunk)
if len(raw) > 2048:
raise HTTPException(413, "Квитанция слишком велика.")
try:
body = json.loads(raw)
except (ValueError, UnicodeDecodeError) as exc:
raise HTTPException(400, "Некорректная квитанция.") from exc
return await run_in_threadpool(
lambda: invoke(store.receipt, invoke(worlds.get, world_id), revision, body)
)
return router