From 43148a8769ce6c6feed45fee8885ff88bcc7bb73 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Sat, 7 Nov 2026 17:31:06 +0300 Subject: [PATCH] Bound semantic map publication and define experiment storage closeout --- docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md | 17 +++++ docs/STORAGE_RETENTION.md | 56 +++++++++++++++ src/k1link/cache_budget.py | 18 +++-- .../simulation/ai_polygon/urban_maps.py | 70 +++++++++++++++---- tests/test_semantic_versions.py | 10 +-- tests/test_urban_maps.py | 67 ++++++++++++++++++ 6 files changed, 215 insertions(+), 23 deletions(-) diff --git a/docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md b/docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md index 72363dee..1a15b0fd 100644 --- a/docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md +++ b/docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md @@ -258,3 +258,20 @@ store/API циклов прошли save/restart; 24 live-файла неизм Последнее поручение владельца: реализовать [автоматическую сборку из примитивов](SEMANTIC_PRIMITIVE_OUTPUT.md) на фиксированном детекторе и показать конечную карту без ручных правок. Это текущая точка продолжения, заменяющая исторический next-step по raw-contour admission/порогам высоты. Root реализует сквозной результат; критик проверяет происхождение, ложные/пропущенные объекты и интеграцию. Наличие одного хорошего кадра, pixel score или тестов не заменяет полный визуальный просмотр объявленного объёма. Никакого нового fit или расширения агентной платформы как обязательного этапа. Пакет `outputs/semantic-primitive-output-20261029`: три сохранённых полноразмерных окна M1/M3/M4, не вся улица и не независимый контроль. Исходные объекты каталога, общие параметры сборки, 2D-распознавание и Gaussian-оценка высоты раздельны. Неподдержанное остаётся unresolved; исходные параметры в редакторе помечены как immutable recognition snapshot, человеческая геометрия живёт отдельно. Новые UI-переключатели отложены; результат даётся отдельным review-артефактом, рабочая пользовательская карта не подменяется. + +## Хранение результатов — уточнение 07.11.2026 + +Перед копированием на Mac root фиксирует назначение, владельца, точный каталог и +конечный лимит экспорта. Распознавание, рендеры, masks/features, подготовка датасета +и обучение остаются на Worker. Core получает версии разметки, конфигурацию, +provenance и квитанции; raw в интерфейсе — геометрическая диагностическая версия. +Ручные ветки и их immutable основы не являются очищаемым scratch. + +Закрытие пакета включает проверяемый closeout: отчёт/решение, хеши входов и кода, +один проверенный текстовый архив, максимум два финальных изображения суммарно до +16 MiB и ссылки на нужные Worker-результаты/rollback. Удаляется только собственный +перечисленный неизменившийся scratch после проверки остановленных владельцев. +Сохраняются индекс восстановления и квитанция удалённых байтов; root проверяет, +что продуктовые карты и ручные правки не изменились. Наличие лимита датасетов в +одном процессе не означает общей квоты всех исследовательских скриптов. +Подробные действующие границы: `docs/STORAGE_RETENTION.md`, раздел аудита 07.11.2026. diff --git a/docs/STORAGE_RETENTION.md b/docs/STORAGE_RETENTION.md index d207a728..4f20777b 100644 --- a/docs/STORAGE_RETENTION.md +++ b/docs/STORAGE_RETENTION.md @@ -302,3 +302,59 @@ hint; receipt identity and hashes permit relocation to a different host. See the provider repository `docs/SOURCE_RETENTION.md` for its API and portability boundary. This supersedes local-original retention for this narrowly defined import flow; other recordings, unique evidence and application data remain protected above. + +## Road-marking and semantic storage — audit 2026-11-07 + +The ordinary infrastructure pipeline renders/infers/assembles on Worker. Core +receives bounded vector maps and job/provenance metadata; the raw UI layer is a +read-only geometry document, not the full RGB/depth/mask dataset. Saving human +edits sends revision packages to the separate Worker learning store, which builds +observations/datasets and returns delivery receipts. Neither path installs a +local training or full-observation fallback. + +Operator-owned durable product data: + +- `ai-polygon/urban-maps`: immutable raw/algorithmic versions, including bases of + manual edits. A shared 1 GiB publication limit and 2 GiB free-space reserve now + cover all scenes. A whole raw/algorithmic pair is admitted together, then its + pointer is replaced atomically. Full storage refuses new versions; it never + removes existing maps. Identical retries and reads remain available at capacity. +- `ai-polygon/semantic-edits`: manual branches, exact revision history and dataset + delivery receipts; existing 64 MiB aggregate/8 MiB state limits remain. +- `ai-polygon/editor-cache`: optimized SOG/collision assets with the existing + 4 GiB publication quota and transfer reservations. Project-backed scenes use + artifact references, not another original-cloud copy. +- App runs, plans and accepted recovery evidence remain application state. Their + names do not make them disposable research cache. + +Engineering exports on Mac must close within the working package: name the owner, +exact staging directory, finite byte allowance and expected output before copy; +retain a concise report, configuration/input hashes, required result/rollback +references, one verified text archive and at most two final proof images (16 MiB +aggregate). Heavy RGB/depth grids, NPZ/logits/features, full point-cloud +adaptations, datasets and checkpoints stay in the separate persistent Worker +store. A full street does not authorize a full local render dump. New unique +result/rollback data need an explicit retained reference; arbitrary old exports +are not automatically protected merely by being called evidence. + +At closeout, verify stopped ownership and every retained archive/member hash; +remove only exact unchanged listed duplicates or explicitly disposable generated +media. Preserve a path-to-hash recovery index and deletion receipt. Do not sweep +by age or remove unknown files. The source-package helper remains source-only; +its caller must remove its own transferred staging after remote identity checks. +This is an engineering closeout obligation, not an automatic whole-disk quota. + +Worker has different stores with different ownership: learning `datasets`, +`inbox`, `sources`, `work`; infrastructure `jobs` and generated source caches; +and historical qualification directories. The learning Store's 20 GiB admission +quota/12 GiB reserve does not constrain arbitrary research writers. Infrastructure +has initial free-space and time checks but currently no aggregate output retention. +Container removal does not remove the data mounts. Do not call those stores +bounded or erase them wholesale: current maps, shared observations, accepted +models/datasets, pending work and rollback require explicit preservation. + +The audit/cleanup index is `outputs/semantic-storage-audit-20261107/REPORT.md`. +The 19 October content-addressed experiment archive remains protected; November +cleanup retires only extra Mac copies verified against that archive, with a +one-file restoration helper. No Worker datasets or qualifications are deleted +by this local cleanup. diff --git a/src/k1link/cache_budget.py b/src/k1link/cache_budget.py index 675ffdcf..e3be03dc 100644 --- a/src/k1link/cache_budget.py +++ b/src/k1link/cache_budget.py @@ -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: diff --git a/src/k1link/simulation/ai_polygon/urban_maps.py b/src/k1link/simulation/ai_polygon/urban_maps.py index b5f6b05d..48121093 100644 --- a/src/k1link/simulation/ai_polygon/urban_maps.py +++ b/src/k1link/simulation/ai_polygon/urban_maps.py @@ -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): diff --git a/tests/test_semantic_versions.py b/tests/test_semantic_versions.py index adfc0373..a861c1de 100644 --- a/tests/test_semantic_versions.py +++ b/tests/test_semantic_versions.py @@ -100,18 +100,18 @@ def test_pair_failure_preserves_pointer_and_ordinary_save_clears_raw(tmp_path, m world, model, maps, _, _ = make_setup(tmp_path) raw, auto = pair(model) previous = maps.versions(world) - original = maps.store_immutable + original = maps._write_immutable - def fail_second(world, document): + def fail_second(world, document, sha): if document.get("semantic_stage") == "algorithmic": raise OSError("interrupted") - return original(world, document) + return original(world, document, sha) - monkeypatch.setattr(maps, "store_immutable", fail_second) + monkeypatch.setattr(maps, "_write_immutable", fail_second) with pytest.raises(OSError): maps.publish_pair(world, raw, auto) assert maps.versions(world) == previous - monkeypatch.setattr(maps, "store_immutable", original) + monkeypatch.setattr(maps, "_write_immutable", original) maps.publish_pair(world, raw, auto) maps.save(world, model) assert "raw_sha256" not in maps.versions(world) diff --git a/tests/test_urban_maps.py b/tests/test_urban_maps.py index 09f2d0ed..9c572a1b 100644 --- a/tests/test_urban_maps.py +++ b/tests/test_urban_maps.py @@ -146,3 +146,70 @@ def test_vector_lines_roundtrip_and_admission(tmp_path): change(bad) with pytest.raises(ValueError): validate_map(bad, world) + + +def test_map_budget_is_global_and_preserves_existing_versions(tmp_path, monkeypatch): + from k1link import cache_budget + + world = {"sha256": "a" * 64} + other = {"sha256": "b" * 64} + store = UrbanMapStore(tmp_path) + first = store.save(world, document(world)) + before = {p.relative_to(store.root).as_posix(): p.read_bytes() + for p in store.root.rglob('*.json')} + monkeypatch.setitem(cache_budget.LIMITS, "urban-maps", 1) + assert store.save(world, document(world)) == first # Exact retry at capacity. + assert store.get(world) == document(world) + with pytest.raises(cache_budget.CacheCapacityError): + store.save(other, document(other)) + after = {p.relative_to(store.root).as_posix(): p.read_bytes() + for p in store.root.rglob('*.json')} + assert after == before + + +def test_pair_budget_checks_both_maps_before_first_write(tmp_path, monkeypatch): + from k1link import cache_budget + + world = {"sha256": "a" * 64} + store = UrbanMapStore(tmp_path) + store.save(world, document(world)) + raw, auto = document(world), document(world) + raw['semantic_stage'], auto['semantic_stage'] = 'raw', 'algorithmic' + before = {p.relative_to(store.root).as_posix(): p.read_bytes() + for p in store.root.rglob('*.json')} + # There is room for raw alone, not the complete atomic publication. + used = cache_budget.usage(store.root)[0] + monkeypatch.setitem(cache_budget.LIMITS, "urban-maps", used + len(json.dumps(raw).encode()) + 1) + with pytest.raises(cache_budget.CacheCapacityError): + store.publish_pair(world, raw, auto) + assert {p.relative_to(store.root).as_posix(): p.read_bytes() + for p in store.root.rglob('*.json')} == before + + +def test_concurrent_identical_publications_recheck_reserved_bytes(tmp_path, monkeypatch): + from concurrent.futures import ThreadPoolExecutor + from contextlib import contextmanager + from threading import Barrier + + from k1link import cache_budget + from k1link.simulation.ai_polygon import urban_maps + + world = {"sha256": "a" * 64} + store = UrbanMapStore(tmp_path) + data, sha, size = store._prepare(world, document(world)) + monkeypatch.setitem(cache_budget.LIMITS, "urban-maps", size + len(json.dumps({'sha256': sha}))) + barrier = Barrier(2) + publish = urban_maps.cache_publication + + @contextmanager + def together(*args, **kwargs): + barrier.wait(timeout=2) # Both callers observed missing files before locking. + with publish(*args, **kwargs): + yield + + monkeypatch.setattr(urban_maps, "cache_publication", together) + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(lambda _: store.save(world, data), range(2))) + assert results[0] == results[1] + assert store.get(world) == data + assert len(list(store.root.rglob('*.json'))) == 2