Bound semantic map publication and define experiment storage closeout
This commit is contained in:
@@ -11,6 +11,7 @@ import os
|
||||
import shutil
|
||||
import stat
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
@@ -26,6 +27,7 @@ LIMITS = {
|
||||
"laboratory-rerun-overlays": 4 * GiB,
|
||||
"observatory-portable-replay-cache": 4 * GiB,
|
||||
"editor-cache": 4 * GiB,
|
||||
"urban-maps": GiB,
|
||||
}
|
||||
FREE_RESERVE = 2 * GiB
|
||||
_LOCK = threading.RLock()
|
||||
@@ -58,7 +60,7 @@ def usage(root: Path) -> tuple[int, int]:
|
||||
@contextmanager
|
||||
def cache_publication(
|
||||
root: Path,
|
||||
additional_bytes: int,
|
||||
additional_bytes: int | Callable[[], int],
|
||||
*,
|
||||
kind=None,
|
||||
limit=None,
|
||||
@@ -70,11 +72,16 @@ def cache_publication(
|
||||
|
||||
additional_bytes includes only bytes not yet in this root; a file renamed
|
||||
within it contributes zero additional bytes. Callers include sidecar overhead.
|
||||
A callable computes the reservation under the publication lock, for writers
|
||||
that must recheck deduplication after waiting for another publisher.
|
||||
Unknown legacy contents stay in place even if already above the new limit.
|
||||
"""
|
||||
root = root.expanduser().absolute()
|
||||
maximum = LIMITS[kind or root.name] if limit is None else limit
|
||||
if type(additional_bytes) is not int or additional_bytes < 0 or maximum < 1:
|
||||
if maximum < 1 or (
|
||||
not callable(additional_bytes)
|
||||
and (type(additional_bytes) is not int or additional_bytes < 0)
|
||||
):
|
||||
raise ValueError("Invalid cache publication budget")
|
||||
ancestor = root
|
||||
while not ancestor.exists():
|
||||
@@ -94,10 +101,13 @@ def cache_publication(
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
reserved = additional_bytes() if callable(additional_bytes) else additional_bytes
|
||||
if type(reserved) is not int or reserved < 0:
|
||||
raise ValueError("Invalid cache publication budget")
|
||||
current, count = usage(root)
|
||||
if current + additional_bytes > maximum or count >= max_files:
|
||||
if current + reserved > maximum or count >= max_files:
|
||||
raise CacheCapacityError("Достигнут лимит кэша. Сохранённые данные не удалены.")
|
||||
if shutil.disk_usage(root).free < additional_bytes + reserve:
|
||||
if shutil.disk_usage(root).free < reserved + reserve:
|
||||
raise CacheCapacityError("Недостаточно свободного места для новой копии кэша.")
|
||||
yield
|
||||
except CacheCapacityError as exc:
|
||||
|
||||
@@ -6,6 +6,7 @@ import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.cache_budget import cache_publication
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
CLASSES = {
|
||||
@@ -148,43 +149,84 @@ class UrbanMapStore:
|
||||
raise ValueError("Invalid world identity")
|
||||
return self.root / key
|
||||
|
||||
def store_immutable(self, world, document):
|
||||
def _prepare(self, world, document):
|
||||
validate_map(document, world)
|
||||
raw = json.dumps(document, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
|
||||
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)
|
||||
path = directory / (sha + ".json")
|
||||
return document, sha, len(raw)
|
||||
|
||||
def _existing(self, world, sha):
|
||||
path = self.directory(world) / (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"])}
|
||||
return True
|
||||
return False
|
||||
|
||||
def _write_immutable(self, world, document, sha):
|
||||
directory = self.directory(world)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
write_json(directory / (sha + ".json"), document)
|
||||
|
||||
def _publish(self, world, prepared, pointer=None):
|
||||
# One admission for the complete pair and its temporary pointer. No
|
||||
# eviction: old versions may still be the base of a manual edit.
|
||||
missing = {}
|
||||
same_pointer = False
|
||||
target = self.directory(world) / "latest.json"
|
||||
|
||||
def reservation():
|
||||
nonlocal missing, same_pointer
|
||||
missing = {sha: (document, size) for document, sha, size in prepared
|
||||
if not self._existing(world, sha)}
|
||||
if target.is_symlink():
|
||||
raise ValueError("Invalid infrastructure pointer")
|
||||
try:
|
||||
same_pointer = pointer is None or json.loads(target.read_text()) == pointer
|
||||
except (FileNotFoundError, ValueError):
|
||||
same_pointer = False
|
||||
pointer_bytes = len(json.dumps(pointer).encode()) if not same_pointer else 0
|
||||
return sum(size for _, size in missing.values()) + pointer_bytes
|
||||
|
||||
if reservation() == 0:
|
||||
return # Exact retry remains available even at/above the budget.
|
||||
with cache_publication(self.root, reservation, kind="urban-maps", max_files=10000):
|
||||
# Recomputed inside the lock: concurrent identical retries reserve no
|
||||
# duplicate bytes and do not rewrite an already published pointer.
|
||||
for sha, (document, _) in missing.items():
|
||||
self._write_immutable(world, document, sha)
|
||||
if pointer is not None and not same_pointer:
|
||||
write_json(target, pointer)
|
||||
|
||||
def store_immutable(self, world, document):
|
||||
prepared = self._prepare(world, document)
|
||||
self._publish(world, [prepared])
|
||||
return {"sha256": prepared[1], "features": len(document["features"])}
|
||||
|
||||
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"]})
|
||||
prepared = self._prepare(world, document)
|
||||
result = {"sha256": prepared[1], "features": len(document["features"])}
|
||||
self._publish(world, [prepared], {"sha256": prepared[1]})
|
||||
return result
|
||||
|
||||
def publish_pair(self, world, raw, algorithmic):
|
||||
"""Publish a complete pair with one atomic pointer replacement."""
|
||||
"""Admit the full pair, then publish through one atomic pointer."""
|
||||
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)
|
||||
raw_prepared = self._prepare(world, raw)
|
||||
prepared = self._prepare(world, algorithmic)
|
||||
pointer = {"sha256": prepared[1], "raw_sha256": raw_prepared[1]}
|
||||
self._publish(world, [raw_prepared, prepared], pointer)
|
||||
return pointer
|
||||
|
||||
def versions(self, world):
|
||||
|
||||
Reference in New Issue
Block a user