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
+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