feat(semantics): version scene edits and refine paint geometry

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:55 +03:00
parent 7a3c3c00b3
commit b7b5ac9cf0
34 changed files with 3014 additions and 138 deletions
@@ -15,6 +15,7 @@ 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}")
BRANCH = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
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.
@@ -229,28 +230,39 @@ class SemanticEdits:
self.root = data_dir / "ai-polygon" / "semantic-edits"
self.maps = maps
def _path(self, world):
def _path(self, world, branch_id=None):
if not HASH.fullmatch(world["sha256"]):
raise ValueError("Некорректная версия сцены.")
return self.root / (world["sha256"] + ".json")
if branch_id is None:
return self.root / (world["sha256"] + ".json")
if not isinstance(branch_id, str) or not BRANCH.fullmatch(branch_id):
raise ValueError("Некорректная ручная версия.")
directory = self.root / world["sha256"] / "branches"
if directory.is_symlink() or directory.parent.is_symlink():
raise ValueError("Недопустимая ссылка на историю.")
return directory / (branch_id + ".json")
def _read(self, world):
path = self._path(world)
def _read(self, world, branch_id=None):
path = self._path(world, branch_id)
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"]
if state.get("branch_id") != branch_id:
raise ValueError("История относится к другой ручной версии.")
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
if (
row.get("branch_id") != branch_id
or digest(payload) != row["revision"]
or row["parent"] != (revisions[i - 1]["revision"] if i else None)
):
raise ValueError("Нарушена целостность истории правок.")
return state
def _model(self, world, sha):
def _model(self, world, sha, *, for_edit=True):
if not isinstance(sha, str) or not HASH.fullmatch(sha):
raise ValueError("Некорректная версия алгоритма.")
path = self.maps.directory(world) / (sha + ".json")
@@ -260,14 +272,16 @@ class SemanticEdits:
if digest(document) != sha:
raise ValueError("Исходная карта изменилась.")
validate_map(document, world)
if for_edit and document.get("semantic_stage") == "raw":
raise ValueError("Сырая алгоритмическая разметка доступна только для просмотра.")
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)
latest_sha = self._latest_sha(world)
sha = revisions[0]["model_sha256"] if revisions else latest_sha
model = self._model(world, sha)
edited = copy.deepcopy(model) if revisions else model
for row in revisions:
@@ -279,7 +293,59 @@ class SemanticEdits:
verified_history=True,
origin=row.get("origin", "human-edit"),
)
return self._response(state, model, edited, sha, digest(latest))
return self._response(state, model, edited, sha, latest_sha)
def _latest_sha(self, world):
# A broken current publication cannot hide an intact pinned manual base.
try:
return digest(self.maps.get(world))
except (FileNotFoundError, ValueError, KeyError):
return None
def _states(self, world):
yield None, self._read(world)
directory = self.root / world["sha256"] / "branches"
if directory.is_symlink() or directory.parent.is_symlink():
raise ValueError("Недопустимая ссылка на историю.")
if directory.exists():
for path in sorted(directory.glob("*.json")):
yield path.stem, self._read(world, path.stem)
def versions(self, world):
try:
pointer = self.maps.versions(world)
for sha in pointer.values():
self.maps.get_version(world, sha)
except (FileNotFoundError, ValueError, KeyError):
pointer = {}
manual = []
for branch_id, state in self._states(world):
if not state["revisions"]:
continue
head = state["revisions"][-1]
manual.append(
{
"branch_id": branch_id,
"revision": head["revision"],
"model_sha256": head["model_sha256"],
"created_at": head["created_at"],
}
)
return {
"raw_sha256": pointer.get("raw_sha256"),
"algorithmic_sha256": pointer.get("sha256"),
"manual": sorted(manual, key=lambda row: row["created_at"], reverse=True),
}
def _find_revision(self, world, revision):
matches = [
(branch, state)
for branch, state in self._states(world)
if any(row["revision"] == revision for row in state["revisions"])
]
if len(matches) != 1:
raise FileNotFoundError("Ревизия не найдена однозначно.")
return matches[0]
@staticmethod
def _response(state, model, edited, sha, latest_sha):
@@ -287,6 +353,7 @@ class SemanticEdits:
head = revisions[-1] if revisions else None
return {
"schema_version": "missioncore.semantic-editor/v1",
"branch_id": state.get("branch_id"),
"model_sha256": sha,
"latest_model_sha256": latest_sha,
"revision": head["revision"] if head else None,
@@ -307,12 +374,33 @@ class SemanticEdits:
},
}
def get(self, world):
return self._view(world, self._read(world))
def get(self, world, source=None, branch_id=None, model_sha256=None):
if source in ("raw", "algorithmic"):
if branch_id is not None:
raise ValueError("Алгоритмическая версия не имеет ручной ветки.")
pointer = self.maps.versions(world)
sha = model_sha256 or pointer.get("raw_sha256" if source == "raw" else "sha256")
if not sha:
raise FileNotFoundError("Эта версия разметки ещё не рассчитана.")
model = self._model(world, sha, for_edit=source != "raw")
if source == "raw" and model.get("semantic_stage") != "raw":
raise ValueError("Версия не является сырой разметкой.")
response = self._response({"revisions": []}, model, model, sha, pointer["sha256"])
if source == "raw":
# Dense diagnostics travel once, never as a duplicate draft.
response.pop("edited")
response["read_only"] = True
return response
if source not in (None, "manual") or model_sha256 is not None:
raise ValueError("Неизвестное представление разметки.")
state = self._read(world, branch_id)
if (source == "manual" or branch_id) and not state["revisions"]:
raise FileNotFoundError("Ручная версия ещё не сохранена.")
return self._view(world, state)
def export(self, world, revision):
"""Portable annotation metadata, explicitly not an image dataset."""
state = self._read(world)
_, state = self._find_revision(world, revision)
index = next(
(i for i, row in enumerate(state["revisions"]) if row["revision"] == revision),
None,
@@ -335,7 +423,7 @@ class SemanticEdits:
return {"sha256": digest(package), "package": package}
def save(self, world, body):
if not isinstance(body, dict) or set(body) - {"origin"} != {
if not isinstance(body, dict) or set(body) - {"origin", "branch_id"} != {
"expected_revision",
"model_sha256",
"request_id",
@@ -347,10 +435,14 @@ class SemanticEdits:
if body.get("origin", "human-edit") not in ("human-edit", "agent-proposal"):
raise ValueError("Некорректное происхождение правки.")
request_hash = digest(body)
branch_id = body.get("branch_id")
self._path(world, branch_id)
# 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)
state = self._read(world, branch_id)
if branch_id is not None:
state["branch_id"] = branch_id
revisions = state["revisions"]
for row in revisions:
if row["request_id"] == body["request_id"]:
@@ -367,7 +459,7 @@ class SemanticEdits:
# 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))
state, model, model, body["model_sha256"], self._latest_sha(world)
)
else:
view = self._view(world, state)
@@ -400,7 +492,9 @@ class SemanticEdits:
self.root
).free < FREE_RESERVE + len(raw):
raise ValueError("Недостаточно места для сохранения правок.")
write_json(self._path(world), state)
path = self._path(world, branch_id)
path.parent.mkdir(parents=True, exist_ok=True)
write_json(path, state)
# Return the exact admitted geometry. Replaying the entire history
# here duplicated work and could fail after a successful commit.
return self._response(
@@ -411,17 +505,18 @@ class SemanticEdits:
"""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"],
}
)
for branch_id, state in self._states(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"],
**({"branch_id": branch_id} if branch_id else {}),
}
)
return sorted(rows, key=lambda r: (r["created_at"], r["revision"]))[:20]
def receipt(self, world, revision, body):
@@ -446,7 +541,7 @@ class SemanticEdits:
package = self.export(world, revision)
if body["package_sha256"] != package["sha256"]:
raise ValueError("Квитанция относится к другой аннотации.")
state = self._read(world)
branch_id, state = self._find_revision(world, revision)
deliveries = state.setdefault("deliveries", {})
previous = deliveries.get(revision)
if previous:
@@ -466,5 +561,5 @@ class SemanticEdits:
or shutil.disk_usage(self.root).free < FREE_RESERVE + len(raw)
):
raise ValueError("Недостаточно места для квитанции.")
write_json(self._path(world), state)
write_json(self._path(world, branch_id), state)
return body
+73 -17
View File
@@ -49,21 +49,25 @@ 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")
if document["schema_version"] == "missioncore.urban-map/v3" and (
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")
cell, cells = coverage.get("cell_m"), coverage.get("accepted_cells")
if type(cell) not in (int, float) or not math.isfinite(cell) or not 0.02 <= cell <= 1:
if type(cell) not in (int, float) or not math.isfinite(cell) or not 0.005 <= cell <= 1:
raise ValueError("Invalid infrastructure sampling resolution")
if type(cells) is not int or not 0 <= cells <= 1_000_000:
raise ValueError("Invalid infrastructure coverage count")
features = document.get("features")
if not isinstance(features, list) or len(features) > 20000:
# Raw is a read-only diagnostic, not an editable object collection. Its
# denser contours have a separate bounded display budget; editable maps
# retain their existing smaller limit.
feature_limit = 50000 if document.get("semantic_stage") == "raw" else 20000
if not isinstance(features, list) or len(features) > feature_limit:
raise ValueError("Invalid infrastructure feature count")
vertices = 0
identifiers = set()
@@ -80,7 +84,10 @@ 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"] in {"missioncore.urban-map/v2", "missioncore.urban-map/v3"}
vector = document["schema_version"] in {
"missioncore.urban-map/v2",
"missioncore.urban-map/v3",
}
if vector:
identifier = feature.get("id")
score = prop.get("confidence")
@@ -125,7 +132,8 @@ def validate_map(document: dict, world: dict) -> dict:
)
):
raise ValueError("Invalid infrastructure XYZ")
if vertices > 300000:
vertex_limit = 400000 if document.get("semantic_stage") == "raw" else 300000
if vertices > vertex_limit:
raise ValueError("Infrastructure map exceeds vertex limit")
return document
@@ -140,25 +148,73 @@ class UrbanMapStore:
raise ValueError("Invalid world identity")
return self.root / key
def save(self, world, document):
def store_immutable(self, world, document):
validate_map(document, world)
raw = json.dumps(document, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
if len(raw) > 12 * 1024**2:
byte_limit = (32 if document.get("semantic_stage") == "raw" else 12) * 1024**2
if len(raw) > byte_limit:
raise ValueError("Infrastructure map exceeds size limit")
sha = hashlib.sha256(raw).hexdigest()
directory = self.directory(world)
directory.mkdir(parents=True, exist_ok=True)
write_json(directory / (sha + ".json"), document)
write_json(directory / "latest.json", {"sha256": sha})
path = directory / (sha + ".json")
if path.is_symlink():
raise ValueError("Invalid infrastructure link")
if path.exists():
self.get_version(world, sha)
else:
write_json(path, document)
return {"sha256": sha, "features": len(document["features"])}
def get(self, world):
def save(self, world, document):
if document.get("semantic_stage") == "raw":
raise ValueError("Raw observations cannot replace the algorithmic map")
result = self.store_immutable(world, document)
write_json(self.directory(world) / "latest.json", {"sha256": result["sha256"]})
return result
def publish_pair(self, world, raw, algorithmic):
"""Publish a complete pair with one atomic pointer replacement."""
for document, stage in ((raw, "raw"), (algorithmic, "algorithmic")):
validate_map(document, world)
if document.get("semantic_stage") != stage:
raise ValueError("Incorrect semantic representation role")
if raw["source"] != algorithmic["source"]:
raise ValueError("Semantic representations must share their source")
raw_result = self.store_immutable(world, raw)
result = self.store_immutable(world, algorithmic)
pointer = {"sha256": result["sha256"], "raw_sha256": raw_result["sha256"]}
write_json(self.directory(world) / "latest.json", pointer)
return pointer
def versions(self, world):
directory = self.directory(world)
sha = json.loads((directory / "latest.json").read_text())["sha256"]
if not re.fullmatch("[0-9a-f]{64}", sha):
path = directory / "latest.json"
if path.is_symlink():
raise ValueError("Invalid infrastructure pointer")
pointer = json.loads(path.read_text())
if (
not isinstance(pointer, dict)
or "sha256" not in pointer
or set(pointer) - {"sha256", "raw_sha256"}
):
raise ValueError("Invalid infrastructure pointer")
for field in ("sha256", "raw_sha256"):
if field in pointer and not re.fullmatch("[0-9a-f]{64}", str(pointer[field])):
raise ValueError("Invalid infrastructure identity")
return pointer
def get_version(self, world, sha):
if not isinstance(sha, str) or not re.fullmatch("[0-9a-f]{64}", sha):
raise ValueError("Invalid infrastructure identity")
document = json.loads((directory / (sha + ".json")).read_text())
path = self.directory(world) / (sha + ".json")
if path.is_symlink():
raise ValueError("Invalid infrastructure link")
document = json.loads(path.read_text())
raw = json.dumps(document, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
if hashlib.sha256(raw).hexdigest() != sha:
raise ValueError("Infrastructure content changed")
return validate_map(document, world)
def get(self, world):
return self.get_version(world, self.versions(world)["sha256"])