refactor(lab): move execution to Worker and manage replay and transfer lifecycles
This commit is contained in:
@@ -11,9 +11,10 @@ import os
|
||||
import shutil
|
||||
import stat
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
GiB = 1024**3
|
||||
MiB = 1024**2
|
||||
@@ -62,12 +63,12 @@ def cache_publication(
|
||||
root: Path,
|
||||
additional_bytes: int | Callable[[], int],
|
||||
*,
|
||||
kind=None,
|
||||
limit=None,
|
||||
reserve=FREE_RESERVE,
|
||||
max_files=10000,
|
||||
error_type=CacheCapacityError,
|
||||
):
|
||||
kind: str | None = None,
|
||||
limit: int | None = None,
|
||||
reserve: int = FREE_RESERVE,
|
||||
max_files: int = 10000,
|
||||
error_type: type[Exception] = CacheCapacityError,
|
||||
) -> Iterator[None]:
|
||||
"""Lock admission through publication. Count temporary bytes already on disk.
|
||||
|
||||
additional_bytes includes only bytes not yet in this root; a file renamed
|
||||
@@ -118,6 +119,6 @@ def cache_publication(
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def require_cache_room(root: Path, additional_bytes=0, **kwargs):
|
||||
def require_cache_room(root: Path, additional_bytes: int = 0, **kwargs: Any) -> None:
|
||||
with cache_publication(root, additional_bytes, **kwargs):
|
||||
pass
|
||||
|
||||
@@ -49,7 +49,7 @@ MAX_SCAN = 512
|
||||
MAX_JSON_BYTES = 64 * 1024 * 1024
|
||||
MAX_LINE_BYTES = 4 * 1024 * 1024
|
||||
MAX_SOURCE_BYTES = 512 * 1024 * 1024
|
||||
OVERLAY_RENDERER_VERSION = "4"
|
||||
OVERLAY_RENDERER_VERSION = "5"
|
||||
OVERLAY_ADMISSION_SCHEMA = "missioncore.e10-overlay-admission/v1"
|
||||
OVERLAY_CACHE_SCHEMA = "missioncore.e10-overlay-cache/v1"
|
||||
CUBOID_PRESENTATION_HOLD_NS = 500_000_000
|
||||
@@ -1088,6 +1088,12 @@ def _camera_proxy_file(
|
||||
str(source),
|
||||
"-vf",
|
||||
frame_filter,
|
||||
# Match the synthetic proxy timestamps instead of inheriting
|
||||
# the source rate, which duplicates/drops selected frames.
|
||||
"-r",
|
||||
"10",
|
||||
"-fps_mode",
|
||||
"cfr",
|
||||
"-an",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Read and restore LAB evidence using the existing immutable artifact format.
|
||||
|
||||
The store belongs to the Worker runtime volume. No host names, drive letters,
|
||||
model execution, automatic downloads or deletion are part of this contract.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath, PureWindowsPath
|
||||
from typing import Any
|
||||
|
||||
from k1link.artifact_gateway import ArtifactIntegrityError, CentralArtifactStore
|
||||
|
||||
INDEX_SCHEMA = "missioncore.laboratory-archive-index/v1"
|
||||
CATALOG_SCHEMA = "missioncore.laboratory-archive-catalog/v1"
|
||||
|
||||
|
||||
def relative_member(value: str) -> PurePosixPath:
|
||||
path = PurePosixPath(value)
|
||||
if not value or path.is_absolute() or ".." in path.parts or "\\" in value:
|
||||
raise ArtifactIntegrityError("unsafe archived relative path")
|
||||
if str(path) != value or ":" in value or "\x00" in value:
|
||||
raise ArtifactIntegrityError("non-canonical archived path")
|
||||
return path
|
||||
|
||||
|
||||
def source_identity(value: str) -> str:
|
||||
"""Validate an opaque original POSIX name, never a restore destination.
|
||||
|
||||
macOS evidence can contain literal Windows paths inside a filename. Keep
|
||||
those names as lookup identities; never interpret their backslashes as
|
||||
filesystem separators on the Worker or reconstruct them automatically.
|
||||
"""
|
||||
if not isinstance(value, str) or not value or len(value) > 8192 or "\x00" in value:
|
||||
raise ArtifactIntegrityError("invalid archived source identity")
|
||||
path = PurePosixPath(value)
|
||||
windows = PureWindowsPath(value)
|
||||
if (path.is_absolute() or ".." in path.parts or str(path) != value
|
||||
or windows.drive or windows.root):
|
||||
raise ArtifactIntegrityError("unsafe archived source identity")
|
||||
return value
|
||||
|
||||
|
||||
class LaboratoryArchiveStore:
|
||||
def __init__(self, root: Path):
|
||||
self.store = CentralArtifactStore(root)
|
||||
|
||||
def catalog(self) -> dict[str, Any]:
|
||||
path = self.store.root / "catalog.json"
|
||||
if path.is_symlink() or path.stat().st_size > 8 * 1024 * 1024:
|
||||
raise ArtifactIntegrityError("unsafe LAB archive catalog")
|
||||
document = json.loads(path.read_bytes())
|
||||
if document.get("schema_version") != CATALOG_SCHEMA:
|
||||
raise ArtifactIntegrityError("unsupported LAB archive catalog")
|
||||
if not isinstance(document.get("groups"), list):
|
||||
raise ArtifactIntegrityError("invalid LAB archive groups")
|
||||
return document
|
||||
|
||||
def find_file(self, relative_path: str) -> str:
|
||||
requested = source_identity(relative_path)
|
||||
matches = []
|
||||
for group in self.catalog()["groups"]:
|
||||
prefix = str(relative_member(group["source_group"]))
|
||||
if requested == prefix or requested.startswith(prefix + "/"):
|
||||
identity = group["manifest_id"]
|
||||
if any(row["path"] == requested for row in self.entries(identity)):
|
||||
matches.append(identity)
|
||||
if len(matches) != 1:
|
||||
raise ArtifactIntegrityError("archive path is absent or ambiguous")
|
||||
return matches[0]
|
||||
|
||||
def entries(self, manifest_id: str) -> list[dict[str, Any]]:
|
||||
manifest = self.store.read_manifest(manifest_id)
|
||||
if manifest.artifact_type != "laboratory-evidence-archive":
|
||||
raise ArtifactIntegrityError("not a LAB evidence archive")
|
||||
index = manifest.member("index")
|
||||
if index.byte_length > 8 * 1024 * 1024:
|
||||
raise ArtifactIntegrityError("oversized LAB archive index")
|
||||
source = self._verified(index.sha256, index.byte_length)
|
||||
document = json.loads(source.read_bytes())
|
||||
if document.get("schema_version") != INDEX_SCHEMA:
|
||||
raise ArtifactIntegrityError("unsupported LAB archive index")
|
||||
rows = document.get("files")
|
||||
if not isinstance(rows, list) or len(rows) > 2000:
|
||||
raise ArtifactIntegrityError("invalid LAB archive member count")
|
||||
paths = set()
|
||||
for row in rows:
|
||||
path = source_identity(row["path"])
|
||||
if path in paths:
|
||||
raise ArtifactIntegrityError("duplicate archived path")
|
||||
paths.add(path)
|
||||
member = manifest.member(row["role"])
|
||||
if member.sha256 != row["sha256"] or member.byte_length != row["bytes"]:
|
||||
raise ArtifactIntegrityError("LAB index and artifact manifest disagree")
|
||||
tombstones = self.store.root / "deleted-members.json"
|
||||
if tombstones.exists():
|
||||
if tombstones.is_symlink() or tombstones.stat().st_size > 8 * 1024**2:
|
||||
raise ArtifactIntegrityError("invalid archive deletion receipt")
|
||||
deleted = json.loads(tombstones.read_bytes())
|
||||
if deleted.get("version") != 1 or not isinstance(deleted.get("paths"), list):
|
||||
raise ArtifactIntegrityError("invalid archive deletion receipt")
|
||||
removed = set(deleted["paths"])
|
||||
rows = [row for row in rows if row["path"] not in removed]
|
||||
return rows
|
||||
|
||||
def verify(self, manifest_id: str) -> dict[str, int]:
|
||||
rows = self.entries(manifest_id)
|
||||
seen = set()
|
||||
total = 0
|
||||
for row in rows:
|
||||
if row["sha256"] not in seen:
|
||||
self._verified(row["sha256"], row["bytes"])
|
||||
seen.add(row["sha256"])
|
||||
total += row["bytes"]
|
||||
return {"files": len(rows), "objects": len(seen), "bytes": total}
|
||||
|
||||
def restore_file(self, manifest_id: str, relative_path: str, destination: Path) -> Path:
|
||||
requested = source_identity(relative_path)
|
||||
rows = [row for row in self.entries(manifest_id) if row["path"] == requested]
|
||||
if len(rows) != 1:
|
||||
raise ArtifactIntegrityError("archived file is not uniquely registered")
|
||||
row = rows[0]
|
||||
source = self._verified(row["sha256"], row["bytes"])
|
||||
target = destination.expanduser().absolute()
|
||||
if target.exists() or target.is_symlink():
|
||||
raise ArtifactIntegrityError("restore destination already exists")
|
||||
if target.parent.resolve(strict=True) != target.parent:
|
||||
raise ArtifactIntegrityError("restore destination contains a symlink")
|
||||
# A restored working copy must never share an inode with immutable evidence.
|
||||
created = False
|
||||
try:
|
||||
with target.open("xb") as out:
|
||||
created = True
|
||||
os.fchmod(out.fileno(), 0o600)
|
||||
digest = hashlib.sha256()
|
||||
with source.open("rb") as inp:
|
||||
for block in iter(lambda: inp.read(1024 * 1024), b""):
|
||||
out.write(block)
|
||||
digest.update(block)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
if digest.hexdigest() != row["sha256"]:
|
||||
raise ArtifactIntegrityError("archive changed during restore")
|
||||
except BaseException:
|
||||
if created:
|
||||
target.unlink(missing_ok=True)
|
||||
raise
|
||||
return target
|
||||
|
||||
def _verified(self, sha: str, size: int) -> Path:
|
||||
path = self.store.object_path(sha)
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size != size:
|
||||
raise ArtifactIntegrityError("archive object missing or wrong size")
|
||||
if path.resolve() != path.absolute():
|
||||
raise ArtifactIntegrityError("archive object has a linked ancestor")
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
if digest.hexdigest() != sha:
|
||||
raise ArtifactIntegrityError("archive object checksum mismatch")
|
||||
return path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Explicit engineering access; never an automatic viewport download."""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--store", type=Path, required=True)
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
commands.add_parser("catalog")
|
||||
verify = commands.add_parser("verify")
|
||||
verify.add_argument("manifest")
|
||||
restore = commands.add_parser("restore-file")
|
||||
restore.add_argument("relative_path")
|
||||
restore.add_argument("destination", type=Path)
|
||||
args = parser.parse_args()
|
||||
store = LaboratoryArchiveStore(args.store)
|
||||
if args.command == "catalog":
|
||||
print(json.dumps(store.catalog(), ensure_ascii=False, indent=2))
|
||||
elif args.command == "verify":
|
||||
print(json.dumps(store.verify(args.manifest)))
|
||||
else:
|
||||
identity = store.find_file(args.relative_path)
|
||||
print(store.restore_file(identity, args.relative_path, args.destination))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Explicit LAB destruction, separate from local presentation-cache expiry.
|
||||
|
||||
Only server-admitted ownership manifests supply paths. HTTP callers supply an
|
||||
opaque owner ID. A durable receipt makes interrupted deletion retryable; shared
|
||||
files survive while another registered owner refers to them. No age-based sweep.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import threading
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,191}\Z")
|
||||
LOCK = threading.RLock()
|
||||
|
||||
|
||||
class LabDeletionError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _identity(value: str) -> str:
|
||||
if not isinstance(value, str) or not _ID.fullmatch(value):
|
||||
raise LabDeletionError("Invalid LAB owner identity")
|
||||
return value
|
||||
|
||||
|
||||
def _read(path: Path):
|
||||
if path.is_symlink() or path.stat().st_size > 32 * 1024**2:
|
||||
raise LabDeletionError("Unsafe LAB ownership document")
|
||||
return json.loads(path.read_bytes())
|
||||
|
||||
|
||||
def _write(path: Path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
with temporary.open("w") as stream:
|
||||
json.dump(value, stream, sort_keys=True)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
class OwnedLabData:
|
||||
"""A portable storage owner, with deployment-bound roots and sealed inventories."""
|
||||
|
||||
def __init__(self, state: Path, roots: dict[str, Path]):
|
||||
self.state = state.absolute()
|
||||
self.roots = {key: value.absolute() for key, value in roots.items()}
|
||||
if self.state.resolve() != self.state or any(
|
||||
value.resolve() != value or not value.is_dir() for value in self.roots.values()
|
||||
):
|
||||
raise LabDeletionError("Linked LAB storage root")
|
||||
|
||||
def _path(self, entry, checked_directories=None):
|
||||
name, relative = entry["root"], entry["path"]
|
||||
if name not in self.roots or not isinstance(relative, str):
|
||||
raise LabDeletionError("Unknown LAB storage root")
|
||||
parts = PurePosixPath(relative)
|
||||
if (not relative or parts.is_absolute() or ".." in parts.parts
|
||||
or str(parts) != relative or "\\" in relative or ":" in relative):
|
||||
raise LabDeletionError("Unsafe LAB storage member")
|
||||
path = self.roots[name] / relative
|
||||
if path == self.roots[name]:
|
||||
raise LabDeletionError("LAB member cannot be its storage root")
|
||||
checked = checked_directories if checked_directories is not None else set()
|
||||
parent = self.roots[name]
|
||||
for part in (None, *parts.parts[:-1]):
|
||||
if part is not None:
|
||||
parent = parent / part
|
||||
if parent in checked:
|
||||
continue
|
||||
try:
|
||||
mode = parent.lstat().st_mode
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
else:
|
||||
if not stat.S_ISDIR(mode):
|
||||
raise LabDeletionError("Linked or invalid LAB storage directory")
|
||||
checked.add(parent)
|
||||
try:
|
||||
mode = path.lstat().st_mode
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
else:
|
||||
if not stat.S_ISREG(mode):
|
||||
raise LabDeletionError("LAB member must be a regular, unlinked file")
|
||||
return path
|
||||
|
||||
def register(self, owner_id: str, files: list[dict], *, complete: bool, refresh: bool = False):
|
||||
"""Internal producer/migration API, never exposed as arbitrary-path HTTP."""
|
||||
owner_id = _identity(owner_id)
|
||||
if not complete:
|
||||
raise LabDeletionError("Incomplete LAB ownership inventory")
|
||||
with LOCK:
|
||||
if (self.state / "receipts" / (owner_id + ".json")).exists():
|
||||
raise LabDeletionError("Deleted LAB identity cannot be republished")
|
||||
normalized = sorted(files, key=lambda row: (row["root"], row["path"]))
|
||||
checked = set()
|
||||
paths = [self._path(row, checked) for row in normalized]
|
||||
if len(paths) != len(set(paths)):
|
||||
raise LabDeletionError("Duplicate LAB storage member")
|
||||
document = {"version": 1, "owner_id": owner_id, "complete": True,
|
||||
"files": normalized}
|
||||
path = self.state / "owners" / (owner_id + ".json")
|
||||
if path.exists() and not refresh and _read(path) != document:
|
||||
raise LabDeletionError("LAB ownership changed")
|
||||
_write(path, document)
|
||||
|
||||
def _owner(self, owner_id):
|
||||
path = self.state / "owners" / (_identity(owner_id) + ".json")
|
||||
if not path.exists():
|
||||
raise LabDeletionError("LAB storage ownership is not registered; nothing removed")
|
||||
document = _read(path)
|
||||
if (document.get("version") != 1 or document.get("owner_id") != owner_id
|
||||
or document.get("complete") is not True):
|
||||
raise LabDeletionError("Invalid LAB ownership manifest")
|
||||
return document
|
||||
|
||||
def prepare(self, owner_ids: list[str]):
|
||||
with LOCK:
|
||||
ids = set(map(_identity, owner_ids))
|
||||
if not ids or len(ids) > 128:
|
||||
raise LabDeletionError("Invalid LAB deletion set")
|
||||
documents = {}
|
||||
for key in ids:
|
||||
receipt = self.state / "receipts" / (key + ".json")
|
||||
if receipt.exists() and _read(receipt).get("state") == "deleted":
|
||||
continue
|
||||
documents[key] = self._owner(key)
|
||||
shared = set()
|
||||
checked = set()
|
||||
for path in (self.state / "owners").glob("*.json"):
|
||||
if path.stem in ids:
|
||||
continue
|
||||
other = self._owner(path.stem)
|
||||
shared.update(self._path(row, checked) for row in other["files"])
|
||||
# Validate all members before deleting any, including shared members.
|
||||
files = {self._path(row, checked) for doc in documents.values() for row in doc["files"]}
|
||||
return documents, sorted(files - shared), len(files & shared)
|
||||
|
||||
def delete(self, owner_ids: list[str]):
|
||||
with LOCK:
|
||||
# Receipts retain only identities/counts, never hidden result payloads.
|
||||
completed = {}
|
||||
pending = []
|
||||
for key in sorted(set(map(_identity, owner_ids))):
|
||||
receipt = self.state / "receipts" / (key + ".json")
|
||||
value = _read(receipt) if receipt.exists() else None
|
||||
if value and value.get("state") == "deleted":
|
||||
completed[key] = value
|
||||
else:
|
||||
pending.append(key)
|
||||
if not pending:
|
||||
return {"state": "deleted", "owners": sorted(completed)}
|
||||
documents, paths, shared = self.prepare(pending)
|
||||
for key in pending:
|
||||
_write(self.state / "receipts" / (key + ".json"),
|
||||
{"version": 1, "owner_id": key, "state": "deleting"})
|
||||
removed_bytes = 0
|
||||
for path in paths:
|
||||
if path.exists():
|
||||
removed_bytes += path.stat().st_size
|
||||
path.unlink()
|
||||
# Remove only empty ancestors below the deployment root.
|
||||
parent = path.parent
|
||||
while parent not in self.roots.values():
|
||||
try:
|
||||
parent.rmdir()
|
||||
except OSError:
|
||||
break
|
||||
parent = parent.parent
|
||||
for key in pending:
|
||||
# Keep ownership until the receipt is committed, for retry after IO failure.
|
||||
_write(self.state / "receipts" / (key + ".json"),
|
||||
{"version": 1, "owner_id": key, "state": "deleted"})
|
||||
(self.state / "owners" / (key + ".json")).unlink(missing_ok=True)
|
||||
return {"state": "deleted", "owners": sorted(set(pending) | set(completed)),
|
||||
"removed_bytes": removed_bytes, "shared_files_retained": shared}
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Coordinate explicit LAB deletion; never equate hiding with destruction."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
|
||||
import httpx
|
||||
|
||||
from k1link.laboratory.data_deletion import LabDeletionError, OwnedLabData, _identity, _write
|
||||
from k1link.laboratory.deletion_inventory import inventory_local
|
||||
from k1link.laboratory.local_presentations import LOCK as PRESENTATION_LOCK
|
||||
|
||||
|
||||
class LabDeletionCoordinator:
|
||||
def __init__(self, *, store, queue, compositions, copies, gateway):
|
||||
self.store, self.queue, self.compositions = store, queue, compositions
|
||||
self.copies, self.gateway = copies, gateway
|
||||
self.state = store.data_dir / "lab-deletions"
|
||||
self.local = OwnedLabData(self.state / "data-ownership", {"core": store.data_dir})
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def _plan(self, kind, identity):
|
||||
if kind == "job":
|
||||
job = self.queue.get(identity)
|
||||
if job.state != "failed" or job.result_id is not None:
|
||||
raise LabDeletionError("Удалять можно только завершённый ошибочный запуск.")
|
||||
return {"owners": [identity], "sessions": [], "jobs": [identity], "copies": []}
|
||||
if kind == "composition":
|
||||
run = self.compositions.get(identity)
|
||||
jobs = [self.queue.get(key) for key in run.job_ids]
|
||||
if any(j.state not in {"failed", "succeeded"} for j in jobs):
|
||||
raise LabDeletionError("Дождитесь завершения запуска.")
|
||||
other_jobs = {key for other in self.compositions.list(include_hidden=False)
|
||||
if other.run_id != identity for key in other.job_ids}
|
||||
exclusive = [j for j in jobs if j.job_id not in other_jobs]
|
||||
sessions = [j.result_id for j in exclusive if j.result_id]
|
||||
return {"owners": [j.job_id for j in exclusive] + sessions,
|
||||
"sessions": sessions, "jobs": [j.job_id for j in exclusive],
|
||||
"copies": [identity] + sessions}
|
||||
self.store.validate_lab_projection(identity)
|
||||
binding = self.store.get_lab_instance(identity)
|
||||
if binding is None:
|
||||
raise LabDeletionError("Выбрана исходная запись, а не LAB.")
|
||||
job_id = binding.provenance.get("job", {}).get("job_id")
|
||||
if job_id and any(job_id in run.job_ids for run in
|
||||
self.compositions.list(include_hidden=False)):
|
||||
raise LabDeletionError("Результат входит в состав LAB. Удалите её целиком.")
|
||||
if job_id and self.queue.get(job_id).state not in {"failed", "succeeded"}:
|
||||
raise LabDeletionError("Дождитесь завершения запуска.")
|
||||
return {"owners": [binding.result_id] + ([job_id] if job_id else []),
|
||||
"sessions": [identity], "jobs": [job_id] if job_id else [],
|
||||
"copies": [binding.result_id]}
|
||||
|
||||
def delete(self, kind: str, identity: str):
|
||||
_identity(identity)
|
||||
if kind not in {"job", "lab", "composition"}:
|
||||
raise LabDeletionError("Неизвестный тип LAB.")
|
||||
with self.lock:
|
||||
path = self.state / (kind + "-" + identity + ".json")
|
||||
previous = json.loads(path.read_text()) if path.exists() else None
|
||||
if previous and previous["state"] == "deleted":
|
||||
return
|
||||
plan = previous["plan"] if previous else self._plan(kind, identity)
|
||||
local_owners = sorted(set(plan["owners"]) | set(plan["copies"]))
|
||||
with PRESENTATION_LOCK:
|
||||
for key in plan["copies"]:
|
||||
if self.copies.leases.get(key, 0):
|
||||
raise LabDeletionError("Закройте просмотр LAB перед удалением.")
|
||||
for key in local_owners:
|
||||
_write(self.state / "blocked" / (key + ".json"), {"deletion": identity})
|
||||
if self.gateway is None:
|
||||
raise LabDeletionError("Worker недоступен. LAB остаётся в списке.")
|
||||
# Missing ownership is a hard failure, never a successful catalog-only delete.
|
||||
if local_owners:
|
||||
if not previous:
|
||||
inventory_local(self.local, local_owners)
|
||||
self.local.prepare(local_owners)
|
||||
_write(path, {"state": "deleting", "plan": plan})
|
||||
receipt = None
|
||||
if plan["owners"]:
|
||||
try:
|
||||
with httpx.Client(base_url=self.gateway.base_url,
|
||||
timeout=httpx.Timeout(600, connect=5),
|
||||
trust_env=False, follow_redirects=False) as client:
|
||||
response = client.post("/api/v1/laboratory/data-deletions",
|
||||
headers={"Authorization": "Bearer " + self.gateway.token()},
|
||||
json={"owner_ids": plan["owners"]})
|
||||
response.raise_for_status()
|
||||
receipt = response.json()
|
||||
if (receipt.get("state") != "deleted"
|
||||
or set(receipt.get("owners", [])) != set(plan["owners"])):
|
||||
raise ValueError("Deletion receipt mismatch")
|
||||
except (httpx.HTTPError, ValueError, OSError) as exc:
|
||||
raise LabDeletionError(
|
||||
"Worker не подтвердил полное удаление. "
|
||||
"LAB остаётся в списке; повторите попытку."
|
||||
) from exc
|
||||
with PRESENTATION_LOCK:
|
||||
if local_owners:
|
||||
self.local.delete(local_owners)
|
||||
for key in plan["copies"]:
|
||||
self.copies.remove(key, delete_lab=True)
|
||||
for key in plan["sessions"]:
|
||||
if self.store.get_lab_instance(key) is not None:
|
||||
self.store.delete_capability_lab_projection(key)
|
||||
for key in plan["jobs"]:
|
||||
self.queue.hide_deleted_projection(key)
|
||||
if kind == "composition":
|
||||
self.compositions.delete_projection(identity)
|
||||
_write(path, {"state": "deleted", "plan": plan, "worker_receipt": receipt})
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Storage adapters for admitted LAB producers, not an arbitrary directory sweep.
|
||||
|
||||
The deployment binds volume names. Each adapter derives ownership from existing
|
||||
sealed result IDs, job directories, artifact manifests or replay sidecars. New
|
||||
producer formats need an adapter; unknown ownership refuses deletion.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.laboratory.archive_store import LaboratoryArchiveStore
|
||||
from k1link.laboratory.data_deletion import LabDeletionError, OwnedLabData, _read, _write
|
||||
|
||||
_JOB = re.compile(r"observatory-run-[a-f0-9]{32}\Z")
|
||||
_RESULT = re.compile(r"(?:e10-integrated-perception|lab-v1-vegetation-shadow|"
|
||||
r"m49-tgs-portable-review|lab-v1-eomt-ddrnet|"
|
||||
r"ai-layer-(?:ddrnet|eomt|rf-detr|object-distance))-[a-f0-9]{64}\Z")
|
||||
|
||||
|
||||
def _files(path: Path):
|
||||
if path.is_symlink():
|
||||
raise LabDeletionError("Linked LAB directory")
|
||||
if path.is_file():
|
||||
return [path]
|
||||
if not path.exists():
|
||||
return []
|
||||
paths = list(path.rglob("*"))
|
||||
if any(p.is_symlink() for p in paths):
|
||||
raise LabDeletionError("Linked LAB member")
|
||||
return [p for p in paths if p.is_file()]
|
||||
|
||||
|
||||
def _add(table, key, root_name, root, paths):
|
||||
table.setdefault(key, set()).update((root_name, p.relative_to(root).as_posix()) for p in paths)
|
||||
|
||||
|
||||
def _replays(table, selected, root_name, root, cache):
|
||||
if not cache.exists():
|
||||
return
|
||||
# Current flat replay cache and legacy session/result playback caches.
|
||||
# Keep depth bounded to admitted layouts; never sweep unrelated source trees.
|
||||
sidecars = [*cache.glob("*.json"), *cache.glob("*/admission.json"),
|
||||
*cache.glob("*/*/*.rrd.cache.json")]
|
||||
for sidecar in sidecars:
|
||||
if sidecar.stat().st_size > 64 * 1024:
|
||||
continue
|
||||
document = _read(sidecar)
|
||||
key = document.get("result_id")
|
||||
if key not in selected:
|
||||
continue
|
||||
# Both canonical overlay and complete-replay sidecars use the same stem.
|
||||
if sidecar.name.endswith(".rrd.cache.json"):
|
||||
payload = sidecar.with_name(sidecar.name.removesuffix(".cache.json"))
|
||||
else:
|
||||
payload = sidecar.with_name(sidecar.name.removesuffix(".json") + ".rrd")
|
||||
files = [sidecar, payload]
|
||||
_add(table, key, root_name, root, [p for p in files if p.exists()])
|
||||
|
||||
|
||||
def _register(store, selected, table):
|
||||
for key in selected:
|
||||
receipt = store.state / "receipts" / (key + ".json")
|
||||
if receipt.exists():
|
||||
continue # Frozen inventory makes partial deletion repeatable.
|
||||
if key not in table:
|
||||
raise LabDeletionError("Не найден полный реестр файлов LAB; удаление отменено.")
|
||||
store.register(key, [{"root": root, "path": path}
|
||||
for root, path in sorted(table[key])], complete=True, refresh=True)
|
||||
|
||||
|
||||
|
||||
def _shared(store, name, selected, table, references):
|
||||
# Only intersecting members can protect bytes in this operation. Do not stat
|
||||
# every member of an unrelated multi-year archive for each single deletion.
|
||||
candidates = set().union(*table.values()) if table else set()
|
||||
for key in selected:
|
||||
owner = store.state / "owners" / (key + ".json")
|
||||
if owner.exists():
|
||||
candidates.update((x["root"], x["path"]) for x in _read(owner)["files"])
|
||||
store.register(name, [{"root": a, "path": b} for a, b in references & candidates],
|
||||
complete=True, refresh=True)
|
||||
|
||||
|
||||
def inventory_local(store: OwnedLabData, selected: list[str]):
|
||||
root = store.roots["core"]
|
||||
selected = set(selected)
|
||||
table = {key: set() for key in selected}
|
||||
cas = root / "observatory-artifact-store"
|
||||
kept = set()
|
||||
for path in (cas / "manifests" / "sha256").glob("*/*.json"):
|
||||
manifest = _read(path)
|
||||
key = manifest.get("subject_id")
|
||||
payloads = [cas / "objects" / "sha256" / m["sha256"][:2] / m["sha256"]
|
||||
for m in manifest["members"]]
|
||||
if key in selected:
|
||||
_add(table, key, "core", root, [path] + payloads)
|
||||
for ref in (cas / "refs").glob("*/*.json"):
|
||||
if _read(ref).get("manifest_id") == path.stem:
|
||||
_add(table, key, "core", root, [ref])
|
||||
else:
|
||||
kept.update(("core", p.relative_to(root).as_posix()) for p in payloads)
|
||||
for key in selected:
|
||||
if _JOB.fullmatch(key):
|
||||
_add(table, key, "core", root,
|
||||
_files(root / "observatory-worker-result-staging" / key))
|
||||
profile = root / "observatory-lab-view-profiles" / (key + ".json")
|
||||
if profile.exists():
|
||||
_add(table, key, "core", root, [profile])
|
||||
for name in ("observatory-portable-replay-cache", "laboratory-rerun-overlays",
|
||||
"integrated-perception-overlays", "perception-overlays"):
|
||||
_replays(table, selected, "core", root, root / name)
|
||||
# A legacy LAB projection could cache a derived source replay under its own
|
||||
# result ID. Retire only that derived product, never original recordings.
|
||||
for key in selected:
|
||||
if not _RESULT.fullmatch(key):
|
||||
continue
|
||||
folder = root / "recordings" / key
|
||||
for sidecar in folder.glob("scene.operator-v12.rrd.cache.json"):
|
||||
document = _read(sidecar)
|
||||
if (document.get("schema_version") != "missioncore.derived-rerun-recording-cache/v12"
|
||||
or document.get("session_id") != key):
|
||||
raise LabDeletionError("Derived LAB recording ownership mismatch")
|
||||
payload = sidecar.with_name(sidecar.name.removesuffix(".cache.json"))
|
||||
_add(table, key, "core", root, [p for p in (sidecar, payload) if p.exists()])
|
||||
_shared(store, "shared-artifact-references", selected, table, kept)
|
||||
_register(store, selected, table)
|
||||
|
||||
|
||||
def inventory_worker(store: OwnedLabData, selected: list[str]):
|
||||
selected = set(selected)
|
||||
table = {key: set() for key in selected if _JOB.fullmatch(key)}
|
||||
lab = store.roots.get("lab")
|
||||
if lab is None:
|
||||
raise LabDeletionError("LAB storage mounts are not configured")
|
||||
collections = (lab / ".runtime/compute-experiments/e10/worker-results",
|
||||
lab / ".runtime/compute-experiments/lab-v1-vegetation/results")
|
||||
for key in selected:
|
||||
for collection in collections:
|
||||
path = collection / key
|
||||
if _RESULT.fullmatch(key) and (path / "result.json").exists():
|
||||
if _read(path / "result.json").get("result_id") != key:
|
||||
raise LabDeletionError("Result ownership mismatch")
|
||||
_add(table, key, "lab", lab, _files(path))
|
||||
for name, patterns in {
|
||||
"ai": ("*/jobs/{id}", "*/sources/{id}"),
|
||||
"tgs": ("*/work/sources/{id}",),
|
||||
}.items():
|
||||
root = store.roots.get(name)
|
||||
if root is None:
|
||||
raise LabDeletionError("Worker job storage mount is unavailable")
|
||||
for key in selected:
|
||||
if not _JOB.fullmatch(key):
|
||||
continue
|
||||
for pattern in patterns:
|
||||
for path in root.glob(pattern.format(id=key)):
|
||||
_add(table, key, name, root, _files(path))
|
||||
# Portable packages carry immutable result identity, irrespective of release directory.
|
||||
for name, pattern in (("tgs",
|
||||
"*/work/m49-portable/runner-output/result-packages/*/manifest.json"),
|
||||
("ai", "*/jobs/*/*/result-staging/manifest.json")):
|
||||
root = store.roots[name]
|
||||
for manifest in root.glob(pattern):
|
||||
if manifest.stat().st_size > 1024 * 1024:
|
||||
continue
|
||||
doc = _read(manifest)
|
||||
key = doc.get("result", {}).get("result_id")
|
||||
if key in selected:
|
||||
_add(table, key, name, root, _files(manifest.parent))
|
||||
for cache in (lab / "presentation").glob("*"):
|
||||
if cache.is_dir():
|
||||
_replays(table, selected, "lab", lab, cache)
|
||||
archive_root = store.roots.get("archive")
|
||||
if archive_root is None:
|
||||
raise LabDeletionError("LAB archive mount is unavailable")
|
||||
archive = LaboratoryArchiveStore(archive_root)
|
||||
retained = set()
|
||||
retired_paths = []
|
||||
for group in archive.catalog()["groups"]:
|
||||
for row in archive.entries(group["manifest_id"]):
|
||||
owners = selected.intersection(Path(row["path"]).parts)
|
||||
path = archive.store.object_path(row["sha256"])
|
||||
if owners:
|
||||
for key in owners:
|
||||
_add(table, key, "archive", archive_root, [path])
|
||||
retired_paths.append(row["path"])
|
||||
else:
|
||||
retained.add(("archive", path.relative_to(archive_root).as_posix()))
|
||||
_shared(store, "shared-archive-references", selected, table, retained)
|
||||
_register(store, selected, table)
|
||||
store.prepare(list(selected))
|
||||
# Persist just path identities before removing bytes. Restore/verify exclude these members.
|
||||
# This prevents a legacy archive from resurrecting a user-deleted LAB.
|
||||
tombstone = archive_root / "deleted-members.json"
|
||||
previous = _read(tombstone) if tombstone.exists() else {"version": 1, "paths": []}
|
||||
previous["paths"] = sorted(set(previous["paths"]) | set(retired_paths))
|
||||
_write(tombstone, previous)
|
||||
@@ -28,10 +28,9 @@ from k1link.laboratory.evidence_registry import (
|
||||
LaboratoryEvidenceRegistry,
|
||||
)
|
||||
from k1link.laboratory.evidence_report import verify_laboratory_evidence_result
|
||||
from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority
|
||||
|
||||
LABORATORY_EXECUTION_REGISTRY_SCHEMA: Final = (
|
||||
"missioncore.laboratory-execution-registry/v1"
|
||||
)
|
||||
LABORATORY_EXECUTION_REGISTRY_SCHEMA: Final = "missioncore.laboratory-execution-registry/v1"
|
||||
LABORATORY_RUN_RECEIPT_SCHEMA: Final = "missioncore.laboratory-run-receipt/v1"
|
||||
LABORATORY_RUN_CONTRACT: Final = "missioncore.laboratory-run/v1"
|
||||
|
||||
@@ -76,9 +75,7 @@ class LaboratoryExecutionDefinition:
|
||||
_identifier(self.work_id, "work_id")
|
||||
if self.lifecycle not in {"canonical", "experimental"}:
|
||||
raise LaboratoryExecutionError("laboratory lifecycle is invalid")
|
||||
expected_isolation = (
|
||||
"core-adapter" if self.lifecycle == "canonical" else "bounded-adapter"
|
||||
)
|
||||
expected_isolation = "core-adapter" if self.lifecycle == "canonical" else "bounded-adapter"
|
||||
if self.isolation != expected_isolation:
|
||||
raise LaboratoryExecutionError(
|
||||
f"{self.lifecycle} laboratory isolation must be {expected_isolation}"
|
||||
@@ -234,7 +231,9 @@ class LaboratoryRunner:
|
||||
sink: PipelineTelemetrySink,
|
||||
adapters: Mapping[str, LaboratoryAdapter] | None = None,
|
||||
clock_ns: Callable[[], int] = time.monotonic_ns,
|
||||
worker_authority: WorkerLaboratoryAuthority | None = None,
|
||||
) -> None:
|
||||
self._worker_authority = worker_authority or WorkerLaboratoryAuthority.from_environment()
|
||||
self._registry = registry
|
||||
self._evidence = {
|
||||
definition.work_id: definition for definition in evidence_registry.definitions
|
||||
@@ -244,6 +243,11 @@ class LaboratoryRunner:
|
||||
self._clock_ns = clock_ns
|
||||
|
||||
def run(self, request: LaboratoryRunRequest) -> LaboratoryRunResult:
|
||||
if self._worker_authority is None:
|
||||
raise LaboratoryExecutionError(
|
||||
"LAB execution requires a Worker; operator execution is disabled"
|
||||
)
|
||||
self._worker_authority.admit_outputs(request.output_root, request.receipt_root)
|
||||
definition = self._registry.executable(request.work_id)
|
||||
_validate_request(request, definition)
|
||||
adapter = self._adapters.get(definition.adapter_id)
|
||||
@@ -599,11 +603,7 @@ def _publish_receipt(
|
||||
document_path = destination / "receipt.json"
|
||||
encoded = _canonical_json(receipt) + b"\n"
|
||||
if destination.exists():
|
||||
if (
|
||||
destination.is_symlink()
|
||||
or document_path.is_symlink()
|
||||
or not document_path.is_file()
|
||||
):
|
||||
if destination.is_symlink() or document_path.is_symlink() or not document_path.is_file():
|
||||
raise LaboratoryExecutionError("existing laboratory receipt is invalid")
|
||||
if document_path.read_bytes() != encoded:
|
||||
raise LaboratoryExecutionError("immutable laboratory receipt changed")
|
||||
@@ -634,9 +634,7 @@ def _definition(value: object) -> LaboratoryExecutionDefinition:
|
||||
contracts = _object(row["contracts"], "laboratory contracts")
|
||||
_exact_keys(contracts, _CONTRACT_KEYS, "laboratory contracts")
|
||||
input_roles = row["input_roles"]
|
||||
if not isinstance(input_roles, list) or not all(
|
||||
isinstance(item, str) for item in input_roles
|
||||
):
|
||||
if not isinstance(input_roles, list) or not all(isinstance(item, str) for item in input_roles):
|
||||
raise LaboratoryExecutionError("laboratory input_roles must be strings")
|
||||
lifecycle = row["lifecycle"]
|
||||
if lifecycle not in {"canonical", "experimental"}:
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Explicit Worker execution placement for supported LAB entry points.
|
||||
|
||||
This is a composition boundary, not a sandbox for arbitrary user Python code.
|
||||
Operator processes have no execution authority by default.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class LaboratoryPlacementError(RuntimeError):
|
||||
"""A LAB attempted to execute outside its configured Worker runtime."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkerLaboratoryAuthority:
|
||||
runtime_root: Path
|
||||
free_reserve_bytes: int = 40 * 1024**3
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls) -> WorkerLaboratoryAuthority | None:
|
||||
if os.environ.get("MISSIONCORE_LAB_RUNTIME_ROLE") != "worker":
|
||||
return None
|
||||
value = os.environ.get("MISSIONCORE_LAB_RUNTIME_ROOT", "")
|
||||
root = Path(value)
|
||||
if not value or not root.is_absolute() or root.resolve() != root or not root.is_dir():
|
||||
raise LaboratoryPlacementError("Worker LAB runtime root is unavailable")
|
||||
return cls(root)
|
||||
|
||||
def admit_outputs(self, *outputs: Path) -> None:
|
||||
root = self.runtime_root
|
||||
if not root.is_absolute() or root.resolve() != root or not root.is_dir():
|
||||
raise LaboratoryPlacementError("Worker LAB runtime root changed")
|
||||
for output in outputs:
|
||||
candidate = output.absolute()
|
||||
if (
|
||||
candidate.resolve() != candidate
|
||||
or not candidate.is_relative_to(root)
|
||||
or candidate == root
|
||||
):
|
||||
raise LaboratoryPlacementError("LAB output escaped the Worker runtime")
|
||||
if shutil.disk_usage(root).free < self.free_reserve_bytes:
|
||||
raise LaboratoryPlacementError("Worker LAB free-space reserve would be exhausted")
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Retention of registered, reproducible LAB playback copies, never LAB evidence.
|
||||
|
||||
Only the renderer can register files. Unknown/legacy files are deliberately not
|
||||
adopted by scanning a directory. Pinning protects the complete merged recording.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
LOCK = threading.RLock()
|
||||
|
||||
|
||||
class LocalPresentationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class LocalPresentations:
|
||||
def __init__(self, data_dir: Path, *, clock: Callable[[], float] = time.time):
|
||||
self.root = data_dir / "observatory-portable-replay-cache"
|
||||
self.index = data_dir / "lab-local-storage.json"
|
||||
self.clock = clock
|
||||
self.leases: dict[str, int] = {}
|
||||
|
||||
def _read(self):
|
||||
if not self.index.exists():
|
||||
return {"version": 1, "retention_days": 30, "entries": {}}
|
||||
if self.index.is_symlink() or self.index.stat().st_size > 8 * 1024**2:
|
||||
raise LocalPresentationError("Индекс локальных копий повреждён.")
|
||||
data = json.loads(self.index.read_text())
|
||||
if data.get("version") != 1 or not isinstance(data.get("entries"), dict):
|
||||
raise LocalPresentationError("Неизвестный формат индекса локальных копий.")
|
||||
return data
|
||||
|
||||
def _write(self, data):
|
||||
self.index.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = self.index.with_suffix(".tmp")
|
||||
with temporary.open("w") as stream:
|
||||
json.dump(data, stream, sort_keys=True)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, self.index)
|
||||
|
||||
def _path(self, name):
|
||||
if not isinstance(name, str) or not re.fullmatch(
|
||||
r"[a-f0-9]{64}(?:\.replay\.rrd|\.json)", name
|
||||
):
|
||||
raise LocalPresentationError("Некорректный путь локальной копии.")
|
||||
path = self.root / name
|
||||
if self.root.resolve() != self.root.absolute() or path.is_symlink():
|
||||
raise LocalPresentationError("Небезопасный путь локальной копии; файл сохранён.")
|
||||
return path
|
||||
|
||||
def _exists(self, entry):
|
||||
try:
|
||||
return bool(entry["files"]) and all(
|
||||
self._path(f["name"]).is_file()
|
||||
and self._path(f["name"]).stat().st_size == f["bytes"]
|
||||
for f in entry["files"]
|
||||
)
|
||||
except (OSError, KeyError, LocalPresentationError):
|
||||
return False
|
||||
|
||||
def register(self, result_id: str, artifact, sidecar: Path):
|
||||
"""Called only after renderer validation; no paths come from HTTP input."""
|
||||
with LOCK:
|
||||
self._require_not_deleted(result_id)
|
||||
data = self._read()
|
||||
previous = data["entries"].get(result_id, {})
|
||||
if previous.get("pinned") and previous.get("sha256") != artifact.sha256:
|
||||
raise LocalPresentationError(
|
||||
"Закреплена другая версия просмотра. Сначала открепите её."
|
||||
)
|
||||
files = []
|
||||
for path, digest in ((artifact.path, artifact.sha256), (sidecar, None)):
|
||||
if path.parent != self.root or self._path(path.name) != path:
|
||||
raise LocalPresentationError("Файл не принадлежит кэшу просмотра.")
|
||||
if digest is None:
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
files.append({"name": path.name, "sha256": digest, "bytes": path.stat().st_size})
|
||||
now = self.clock()
|
||||
# Persist access at most once per minute during range requests.
|
||||
if (
|
||||
previous.get("sha256") == artifact.sha256
|
||||
and now - previous.get("last_used", 0) < 60
|
||||
):
|
||||
return
|
||||
data["entries"][result_id] = {
|
||||
"files": files,
|
||||
"sha256": artifact.sha256,
|
||||
"bytes": artifact.byte_length,
|
||||
"last_used": now,
|
||||
"pinned": bool(previous.get("pinned")),
|
||||
}
|
||||
self._write(data)
|
||||
|
||||
def snapshot(self):
|
||||
with LOCK:
|
||||
data = self._read()
|
||||
return {
|
||||
"retention_days": data["retention_days"],
|
||||
"entries": {
|
||||
key: {
|
||||
"local": self._exists(value),
|
||||
"pinned": value["pinned"],
|
||||
"bytes": value["bytes"],
|
||||
"last_used": value["last_used"],
|
||||
}
|
||||
for key, value in data["entries"].items()
|
||||
},
|
||||
}
|
||||
|
||||
def policy(self, days: int):
|
||||
if type(days) is not int or not 1 <= days <= 365:
|
||||
raise LocalPresentationError("Срок хранения — от 1 до 365 дней.")
|
||||
with LOCK:
|
||||
data = self._read()
|
||||
data["retention_days"] = days
|
||||
self._write(data)
|
||||
return self.snapshot()
|
||||
|
||||
def pin(self, result_id: str, value: bool):
|
||||
with LOCK:
|
||||
data = self._read()
|
||||
entry = data["entries"].get(result_id)
|
||||
if entry is None or (value and not self._exists(entry)):
|
||||
raise LocalPresentationError("Сначала подготовьте полную запись просмотра.")
|
||||
if value:
|
||||
for file in entry["files"]:
|
||||
with self._path(file["name"]).open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != file["sha256"]:
|
||||
raise LocalPresentationError(
|
||||
"Локальная копия не прошла проверку целостности."
|
||||
)
|
||||
entry["pinned"] = value
|
||||
entry["last_used"] = self.clock() # Unpin starts a full retention interval.
|
||||
self._write(data)
|
||||
return self.snapshot()
|
||||
|
||||
def _require_not_deleted(self, result_id: str):
|
||||
if (self.index.parent / "lab-deletions" / "blocked" / (result_id + ".json")).exists():
|
||||
raise LocalPresentationError("LAB удаляется или уже удалена.")
|
||||
|
||||
def acquire(self, result_id: str):
|
||||
with LOCK:
|
||||
self._require_not_deleted(result_id)
|
||||
self.leases[result_id] = self.leases.get(result_id, 0) + 1
|
||||
|
||||
def release(self, result_id: str):
|
||||
with LOCK:
|
||||
self.leases[result_id] = max(0, self.leases.get(result_id, 0) - 1)
|
||||
|
||||
@contextmanager
|
||||
def use(self, result_id: str):
|
||||
self.acquire(result_id)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.release(result_id)
|
||||
|
||||
def remove(self, result_id: str, *, delete_lab: bool = False):
|
||||
with LOCK:
|
||||
data = self._read()
|
||||
entry = data["entries"].get(result_id)
|
||||
if entry is None:
|
||||
return self.snapshot()
|
||||
if (entry["pinned"] and not delete_lab) or self.leases.get(result_id, 0):
|
||||
raise LocalPresentationError("Копия закреплена или сейчас используется.")
|
||||
# Validate every file before deleting any. Never erase a changed/unknown file.
|
||||
paths = []
|
||||
for file in entry["files"]:
|
||||
path = self._path(file["name"])
|
||||
if path.exists():
|
||||
with path.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != file["sha256"]:
|
||||
raise LocalPresentationError(
|
||||
"Копия изменилась; автоматическое удаление отменено."
|
||||
)
|
||||
paths.append(path)
|
||||
shared = {
|
||||
file["name"]
|
||||
for key, value in data["entries"].items()
|
||||
if key != result_id
|
||||
for file in value["files"]
|
||||
}
|
||||
for path in paths:
|
||||
if path.name not in shared:
|
||||
path.unlink()
|
||||
entry["files"] = []
|
||||
entry["bytes"] = 0
|
||||
entry["sha256"] = None
|
||||
if delete_lab:
|
||||
del data["entries"][result_id]
|
||||
self._write(data)
|
||||
return self.snapshot()
|
||||
|
||||
def prune(self):
|
||||
with LOCK:
|
||||
data = self._read()
|
||||
expired = [
|
||||
key
|
||||
for key, value in data["entries"].items()
|
||||
if value["files"]
|
||||
and not value["pinned"]
|
||||
and not self.leases.get(key, 0)
|
||||
and self.clock() - value["last_used"] >= data["retention_days"] * 86400
|
||||
]
|
||||
for key in expired:
|
||||
try:
|
||||
self.remove(key)
|
||||
except (OSError, LocalPresentationError):
|
||||
continue # A changed file requires inspection, never blind cleanup.
|
||||
return len(expired)
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Explicit hash-verified LAB compatibility restore on Worker, never Core."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.artifact_gateway import ArtifactIntegrityError
|
||||
from k1link.laboratory.archive_store import LaboratoryArchiveStore, relative_member
|
||||
|
||||
ROOTS = {
|
||||
".runtime/compute-experiments",
|
||||
".runtime/compute-jobs",
|
||||
".runtime/compute-results",
|
||||
".runtime/worker-results",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--archive", type=Path, required=True)
|
||||
p.add_argument("--target", type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
if os.environ.get("MISSIONCORE_LAB_RUNTIME_ROLE") != "worker":
|
||||
raise RuntimeError("Worker only")
|
||||
archive = LaboratoryArchiveStore(a.archive)
|
||||
a.target.mkdir(parents=True, exist_ok=True)
|
||||
if a.target.resolve() != a.target.absolute():
|
||||
raise RuntimeError("Linked target")
|
||||
state = a.target / "state"
|
||||
state.mkdir(exist_ok=True)
|
||||
owner = state / "ownership.json"
|
||||
contract = {
|
||||
"schema_version": "missioncore.laboratory-runtime-volume/v1",
|
||||
"owner": "mission-core-laboratory",
|
||||
"role": "worker",
|
||||
"budget_bytes": 128 * 1024**3,
|
||||
"free_reserve_bytes": 40 * 1024**3,
|
||||
"legacy_archive_catalog_sha256": hashlib.sha256(
|
||||
(a.archive / "catalog.json").read_bytes()
|
||||
).hexdigest(),
|
||||
}
|
||||
if owner.exists() and json.loads(owner.read_text()) != contract:
|
||||
raise RuntimeError("Different volume owner")
|
||||
owner.write_text(json.dumps(contract, indent=2))
|
||||
rows = []
|
||||
skipped = []
|
||||
for group in archive.catalog()["groups"]:
|
||||
if not any(
|
||||
group["source_group"] == root or group["source_group"].startswith(root + "/")
|
||||
for root in ROOTS
|
||||
):
|
||||
continue
|
||||
for row in archive.entries(group["manifest_id"]):
|
||||
try:
|
||||
relative_member(row["path"])
|
||||
except ArtifactIntegrityError:
|
||||
skipped.append(row["path"])
|
||||
continue
|
||||
if Path(row["path"]).name == ".DS_Store":
|
||||
continue
|
||||
rows.append(row)
|
||||
total = sum(r["bytes"] for r in rows)
|
||||
if (
|
||||
total > contract["budget_bytes"]
|
||||
or shutil.disk_usage(a.target).free < total + contract["free_reserve_bytes"]
|
||||
):
|
||||
raise RuntimeError("Restore budget exceeded")
|
||||
started = time.time()
|
||||
done = 0
|
||||
for i, row in enumerate(rows):
|
||||
src = archive.store.object_path(row["sha256"])
|
||||
dst = a.target / row["path"]
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dst.parent.resolve() != dst.parent or dst.is_symlink():
|
||||
raise RuntimeError("Unsafe destination")
|
||||
if dst.exists():
|
||||
with dst.open("rb") as f:
|
||||
sha = hashlib.file_digest(f, "sha256").hexdigest()
|
||||
if dst.stat().st_size != row["bytes"] or sha != row["sha256"]:
|
||||
raise RuntimeError("Existing output differs: " + row["path"])
|
||||
else:
|
||||
temp = dst.with_name(dst.name + ".restoring")
|
||||
with src.open("rb") as inp, temp.open("wb") as out:
|
||||
d = hashlib.sha256()
|
||||
for block in iter(lambda: inp.read(4 * 1024**2), b""):
|
||||
d.update(block)
|
||||
out.write(block)
|
||||
if temp.stat().st_size != row["bytes"] or d.hexdigest() != row["sha256"]:
|
||||
raise RuntimeError("Archive payload differs")
|
||||
os.replace(temp, dst)
|
||||
done += row["bytes"]
|
||||
if i % 5000 == 0:
|
||||
print(json.dumps({"files": i, "bytes": done}), flush=True)
|
||||
receipt = {
|
||||
"schema_version": "missioncore.laboratory-materialization/v1",
|
||||
"catalog_sha256": contract["legacy_archive_catalog_sha256"],
|
||||
"files": len(rows),
|
||||
"bytes": total,
|
||||
"skipped_opaque_names": skipped,
|
||||
"seconds": round(time.time() - started, 2),
|
||||
"complete": True,
|
||||
}
|
||||
(state / "materialization.json").write_text(json.dumps(receipt, indent=2))
|
||||
print(json.dumps(receipt), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Install digest-bound LAB camera inputs from existing Worker CAS stores only."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.laboratory.archive_store import relative_member
|
||||
from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority
|
||||
from k1link.laboratory.worker_recorded_sources import WorkerRecordedSources
|
||||
|
||||
|
||||
def _digest(value: str) -> str:
|
||||
if not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value):
|
||||
raise ValueError("Invalid source digest")
|
||||
return value
|
||||
|
||||
|
||||
def _install(source: Path, target: Path, digest: str, size: int) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.resolve() != target.absolute() or source.resolve() != source.absolute():
|
||||
raise ValueError("Linked camera source or target")
|
||||
if target.exists():
|
||||
source = target
|
||||
if not source.is_file() or source.stat().st_size != size:
|
||||
raise ValueError("Camera source size mismatch")
|
||||
with source.open("rb") as f:
|
||||
if hashlib.file_digest(f, "sha256").hexdigest() != digest:
|
||||
raise ValueError("Camera source digest mismatch")
|
||||
if source != target:
|
||||
temporary = target.with_name(target.name + ".installing")
|
||||
if temporary.is_symlink():
|
||||
raise ValueError("Linked installation temporary")
|
||||
shutil.copyfile(source, temporary)
|
||||
with temporary.open("rb") as f:
|
||||
if hashlib.file_digest(f, "sha256").hexdigest() != digest:
|
||||
raise ValueError("Camera copy digest mismatch")
|
||||
os.replace(temporary, target)
|
||||
|
||||
|
||||
def install(
|
||||
import_path: Path,
|
||||
target: Path,
|
||||
archive: Path,
|
||||
cache: Path,
|
||||
*,
|
||||
expected_bindings_sha: str | None = None,
|
||||
) -> dict:
|
||||
authority = WorkerLaboratoryAuthority.from_environment()
|
||||
if authority is None:
|
||||
raise RuntimeError("Camera materialization requires Worker execution")
|
||||
authority.admit_outputs(target)
|
||||
if import_path.stat().st_size > 32 * 1024**2:
|
||||
raise ValueError("Oversized source import")
|
||||
doc = json.loads(import_path.read_bytes())
|
||||
if doc.get("schema_version") != "missioncore.laboratory-recorded-source-import/v1":
|
||||
raise ValueError("Unsupported source import")
|
||||
planned = []
|
||||
for media_id, members in doc["media"].items():
|
||||
_digest(media_id)
|
||||
for row in members:
|
||||
rel = relative_member(row["path"])
|
||||
sha = _digest(row["sha256"])
|
||||
size = row["bytes"]
|
||||
if not isinstance(size, int) or isinstance(size, bool) or not 0 < size <= 64 * 1024**2:
|
||||
raise ValueError("Invalid media object size")
|
||||
candidates = (archive / "objects" / "sha256" / sha[:2] / sha, cache / sha)
|
||||
source = next((p for p in candidates if p.is_file()), None)
|
||||
planned.append((source, target / "media" / media_id / rel, sha, size))
|
||||
missing = sum(source is None for source, *_ in planned)
|
||||
if missing:
|
||||
raise ValueError(f"Worker CAS lacks {missing} of {len(planned)} camera members")
|
||||
total = sum(row[3] for row in planned)
|
||||
if (
|
||||
total > 16 * 1024**3
|
||||
or shutil.disk_usage(authority.runtime_root).free < total + 40 * 1024**3
|
||||
):
|
||||
raise ValueError("Camera materialization budget exceeded")
|
||||
for i, (source, destination, sha, size) in enumerate(planned):
|
||||
_install(source, destination, sha, size)
|
||||
if i % 5000 == 0:
|
||||
print(json.dumps({"camera_members": i, "total": len(planned)}), flush=True)
|
||||
for sha, text in doc["descriptors"].items():
|
||||
_digest(sha)
|
||||
data = text.encode()
|
||||
if len(data) > 16 * 1024**2 or hashlib.sha256(data).hexdigest() != sha:
|
||||
raise ValueError("Invalid camera descriptor")
|
||||
path = target / "descriptors" / f"{sha}.json"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.resolve() != path.absolute() or (path.exists() and path.read_bytes() != data):
|
||||
raise ValueError("Camera descriptor conflict")
|
||||
path.write_bytes(data)
|
||||
sources = WorkerRecordedSources(target, bindings_document=doc["bindings"])
|
||||
for session, name in sources.bindings:
|
||||
sources.manifest(session, name)
|
||||
bindings = target / "bindings.json"
|
||||
payload = json.dumps(doc["bindings"], sort_keys=True).encode()
|
||||
if (bindings.exists() and bindings.read_bytes() != payload and (
|
||||
not expected_bindings_sha
|
||||
or hashlib.sha256(bindings.read_bytes()).hexdigest() != expected_bindings_sha)):
|
||||
raise ValueError("Source bindings changed since reviewed import")
|
||||
temporary = bindings.with_suffix(".installing")
|
||||
temporary.write_bytes(payload)
|
||||
os.replace(temporary, bindings)
|
||||
receipt = {
|
||||
"schema_version": "missioncore.laboratory-camera-materialization/v1",
|
||||
"bindings": len(sources.bindings),
|
||||
"members": len(planned),
|
||||
"bytes": total,
|
||||
"import_sha256": hashlib.sha256(import_path.read_bytes()).hexdigest(),
|
||||
"bindings_sha256": hashlib.sha256(payload).hexdigest(),
|
||||
"complete": True,
|
||||
}
|
||||
(target / "receipt.json").write_text(json.dumps(receipt, indent=2))
|
||||
return receipt
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ("import-file", "target", "archive", "cache"):
|
||||
parser.add_argument("--" + name, type=Path, required=True)
|
||||
parser.add_argument("--expected-bindings-sha")
|
||||
a = parser.parse_args()
|
||||
print(
|
||||
json.dumps(
|
||||
install(
|
||||
a.import_file,
|
||||
a.target,
|
||||
a.archive,
|
||||
a.cache,
|
||||
expected_bindings_sha=a.expected_bindings_sha,
|
||||
)
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Bounded operator transport for Worker-owned laboratory routes.
|
||||
|
||||
No filesystem evidence reader, model runner, automatic retry of writes or local
|
||||
compute fallback is part of this module. Responses are streamed without staging
|
||||
whole datasets on the operator disk.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
MAX_REQUEST_BYTES = 8 * 1024 * 1024
|
||||
MAX_RESPONSE_BYTES = 2 * 1024 * 1024 * 1024
|
||||
_HEADERS = frozenset(
|
||||
{
|
||||
"content-type",
|
||||
"content-length",
|
||||
"content-range",
|
||||
"accept-ranges",
|
||||
"etag",
|
||||
"last-modified",
|
||||
"cache-control",
|
||||
"content-disposition",
|
||||
"content-encoding",
|
||||
"x-rerun-format",
|
||||
"x-uncompressed-content-length",
|
||||
"x-content-type-options",
|
||||
}
|
||||
)
|
||||
_REQUEST_HEADERS = frozenset(
|
||||
{
|
||||
"range",
|
||||
"if-none-match",
|
||||
"if-modified-since",
|
||||
"if-range",
|
||||
"if-match",
|
||||
"content-type",
|
||||
"accept",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LaboratoryGatewayConfiguration:
|
||||
base_url: str
|
||||
token_file: Path
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
url = urlsplit(self.base_url)
|
||||
if (
|
||||
url.scheme not in {"http", "https"}
|
||||
or not url.hostname
|
||||
or url.username
|
||||
or url.password
|
||||
or url.query
|
||||
or url.fragment
|
||||
or url.path not in {"", "/"}
|
||||
):
|
||||
raise ValueError("Invalid LAB worker endpoint")
|
||||
if url.scheme == "http" and url.hostname not in {"127.0.0.1", "::1", "localhost"}:
|
||||
raise ValueError("Plain HTTP LAB transport requires a loopback SSH tunnel")
|
||||
|
||||
@classmethod
|
||||
def from_file(cls, path: Path) -> LaboratoryGatewayConfiguration:
|
||||
if path.is_symlink() or path.stat().st_size > 8192:
|
||||
raise ValueError("Invalid LAB gateway configuration")
|
||||
value = json.loads(path.read_text())
|
||||
if (
|
||||
set(value) != {"schema_version", "base_url", "token_file"}
|
||||
or value["schema_version"] != "missioncore.laboratory-worker-gateway/v1"
|
||||
):
|
||||
raise ValueError("Unsupported LAB gateway configuration")
|
||||
token_file = Path(value["token_file"])
|
||||
if not token_file.is_absolute():
|
||||
token_file = path.parent / token_file
|
||||
return cls(value["base_url"], token_file)
|
||||
|
||||
def token(self) -> str:
|
||||
path = self.token_file
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size > 512:
|
||||
raise ValueError("LAB worker credential unavailable")
|
||||
token = path.read_text().strip()
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{40,256}", token):
|
||||
raise ValueError("Invalid LAB worker credential")
|
||||
return token
|
||||
|
||||
|
||||
class LaboratoryWorkerGateway:
|
||||
def __init__(
|
||||
self,
|
||||
configuration: LaboratoryGatewayConfiguration | None,
|
||||
*,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
) -> None:
|
||||
self.configuration = configuration
|
||||
self.transport = transport
|
||||
self._capacity = asyncio.Semaphore(8)
|
||||
|
||||
async def forward(
|
||||
self, request: Request, path: str, *, namespace: str = "laboratory"
|
||||
) -> StreamingResponse:
|
||||
if namespace not in {"laboratory", "lidar"}:
|
||||
raise ValueError("Invalid Worker namespace")
|
||||
if self.configuration is None:
|
||||
raise HTTPException(
|
||||
503, "Worker лабораторий не настроен. Локальное выполнение отключено."
|
||||
)
|
||||
# Do not let a path change the configured upstream origin or escape LAB.
|
||||
if "\\" in path or any(p in {".", ".."} for p in path.split("/")):
|
||||
raise HTTPException(400, "Некорректный путь LAB.")
|
||||
body = bytearray()
|
||||
async for part in request.stream():
|
||||
if len(body) + len(part) > MAX_REQUEST_BYTES:
|
||||
raise HTTPException(413, "Запрос LAB превышает допустимый размер.")
|
||||
body.extend(part)
|
||||
try:
|
||||
token = self.configuration.token()
|
||||
except (OSError, ValueError) as exc:
|
||||
raise HTTPException(503, "Подключение Worker лабораторий недоступно.") from exc
|
||||
try:
|
||||
await asyncio.wait_for(self._capacity.acquire(), timeout=2)
|
||||
except TimeoutError:
|
||||
raise HTTPException(503, "Worker лабораторий занят.") from None
|
||||
client = httpx.AsyncClient(
|
||||
base_url=self.configuration.base_url,
|
||||
transport=self.transport,
|
||||
timeout=httpx.Timeout(360 if path.endswith(".rrd") else 60, connect=5),
|
||||
follow_redirects=False,
|
||||
trust_env=False,
|
||||
limits=httpx.Limits(max_connections=8, max_keepalive_connections=0),
|
||||
)
|
||||
headers = {
|
||||
k: v
|
||||
for k, v in request.headers.items()
|
||||
if k.lower() in _REQUEST_HEADERS or k.lower().startswith("x-m48-")
|
||||
}
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
headers["Accept-Encoding"] = "identity"
|
||||
# URL construction is relative to a fixed root; query remains opaque bytes.
|
||||
url = httpx.URL(self.configuration.base_url).copy_with(
|
||||
path="/api/v1/" + namespace + "/" + path,
|
||||
query=request.scope.get("query_string", b""),
|
||||
)
|
||||
try:
|
||||
response = await client.send(
|
||||
client.build_request(request.method, url, headers=headers, content=bytes(body)),
|
||||
stream=True,
|
||||
)
|
||||
if response.headers.get("content-encoding", "identity") not in {"identity", "gzip"}:
|
||||
raise ValueError("Unsupported upstream content encoding")
|
||||
size = response.headers.get("content-length")
|
||||
if size is not None and (not size.isdecimal() or int(size) > MAX_RESPONSE_BYTES):
|
||||
raise ValueError("LAB result exceeds transfer budget")
|
||||
if 300 <= response.status_code < 400 and response.status_code != 304:
|
||||
raise ValueError("LAB worker redirects are not admitted")
|
||||
except BaseException as exc:
|
||||
await client.aclose()
|
||||
self._capacity.release()
|
||||
if not isinstance(exc, (httpx.HTTPError, ValueError)):
|
||||
raise
|
||||
raise HTTPException(
|
||||
503, "Worker лабораторий недоступен или вернул некорректный результат."
|
||||
) from None
|
||||
|
||||
closed = False
|
||||
|
||||
async def close() -> None:
|
||||
nonlocal closed
|
||||
if not closed:
|
||||
closed = True
|
||||
try:
|
||||
await response.aclose()
|
||||
await client.aclose()
|
||||
finally:
|
||||
self._capacity.release()
|
||||
|
||||
async def stream():
|
||||
received = 0
|
||||
try:
|
||||
chunks = (
|
||||
response.aiter_bytes() if response.is_stream_consumed else response.aiter_raw()
|
||||
)
|
||||
async for chunk in chunks:
|
||||
received += len(chunk)
|
||||
if received > MAX_RESPONSE_BYTES:
|
||||
raise RuntimeError("LAB response exceeded the transfer budget")
|
||||
yield chunk
|
||||
finally:
|
||||
await close()
|
||||
|
||||
return StreamingResponse(
|
||||
stream(),
|
||||
status_code=response.status_code,
|
||||
headers={
|
||||
k: v
|
||||
for k, v in response.headers.items()
|
||||
if k.lower() in _HEADERS or k.lower().startswith("x-m48-")
|
||||
},
|
||||
background=BackgroundTask(close),
|
||||
)
|
||||
|
||||
|
||||
def build_laboratory_worker_gateway_router(
|
||||
gateway: LaboratoryWorkerGateway, *, namespace: str = "laboratory"
|
||||
) -> APIRouter:
|
||||
if namespace not in {"laboratory", "lidar"}:
|
||||
raise ValueError("Invalid Worker namespace")
|
||||
router = APIRouter(prefix="/api/v1/" + namespace, tags=["laboratory"])
|
||||
|
||||
@router.api_route("/{path:path}", methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"])
|
||||
async def proxy(request: Request, path: str):
|
||||
return await gateway.forward(request, path, namespace=namespace)
|
||||
|
||||
return router
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Digest-bound recorded camera bindings for the Worker LAB viewer.
|
||||
|
||||
Uses the same prepared-media validator and exact-fragment decoder as the
|
||||
operator viewer. There is no session database copy or source download fallback.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.laboratory.archive_store import relative_member
|
||||
from k1link.sessions.media import RecordedMediaManifest, _manifest_from_sidecar
|
||||
from k1link.sessions.models import RecordedMediaArtifact, SessionIntegrityError
|
||||
|
||||
|
||||
class WorkerRecordedSources:
|
||||
def __init__(self, root: Path, *, bindings_document: dict | None = None):
|
||||
self.root = root.resolve(strict=True)
|
||||
if bindings_document is None:
|
||||
path = self.root / "bindings.json"
|
||||
if path.is_symlink() or path.stat().st_size > 1024**2:
|
||||
raise SessionIntegrityError("Invalid Worker camera bindings")
|
||||
document = json.loads(path.read_bytes())
|
||||
else:
|
||||
document = bindings_document
|
||||
if document.get("schema_version") != "missioncore.laboratory-recorded-source-bindings/v1":
|
||||
raise SessionIntegrityError("Unsupported Worker camera bindings")
|
||||
self.bindings = {}
|
||||
for row in document["sources"]:
|
||||
key = (row["session_id"], row["source_name"])
|
||||
if key in self.bindings:
|
||||
raise SessionIntegrityError("Ambiguous Worker source")
|
||||
self.bindings[key] = row
|
||||
|
||||
def manifest(self, session_id: str, source_name: str) -> RecordedMediaManifest:
|
||||
binding = self.bindings.get((session_id, source_name))
|
||||
if binding is None:
|
||||
raise SessionIntegrityError("Camera source is not installed on Worker")
|
||||
path = self.root / relative_member(binding["descriptor"])
|
||||
if path.resolve() != path or path.stat().st_size > 16 * 1024**2:
|
||||
raise SessionIntegrityError("Invalid Worker camera descriptor")
|
||||
payload = path.read_bytes()
|
||||
if hashlib.sha256(payload).hexdigest() != binding["descriptor_sha256"]:
|
||||
raise SessionIntegrityError("Worker camera descriptor changed")
|
||||
doc = json.loads(payload)
|
||||
source = self.root / relative_member(binding["media_root"])
|
||||
if source.resolve() != source or not source.is_dir():
|
||||
raise SessionIntegrityError("Worker camera source changed")
|
||||
artifact = RecordedMediaArtifact(
|
||||
session_id=session_id,
|
||||
public_source_id=doc["public_source_id"],
|
||||
artifact_id=doc["artifact_id"],
|
||||
source_path=source,
|
||||
byte_length=doc["manifest"]["byte_length"],
|
||||
)
|
||||
epochs = tuple(source / f"epoch-{i + 1}" for i in range(len(doc["manifest"]["epochs"])))
|
||||
return _manifest_from_sidecar(doc, artifact, epochs)
|
||||
|
||||
|
||||
class WorkerCanonicalRecordings:
|
||||
"""Verified ready RRDs used as LAB presentation inputs; never synthesized here."""
|
||||
|
||||
def __init__(self, root: Path):
|
||||
self.root = root.resolve(strict=True)
|
||||
path = self.root / "canonical-recordings.json"
|
||||
self.rows = {}
|
||||
if not path.is_file():
|
||||
return
|
||||
if path.is_symlink() or path.stat().st_size > 1024**2:
|
||||
raise SessionIntegrityError("Invalid canonical recording index")
|
||||
doc = json.loads(path.read_bytes())
|
||||
if doc.get("schema_version") != "missioncore.laboratory-canonical-recordings/v1":
|
||||
raise SessionIntegrityError("Unsupported canonical recording index")
|
||||
for row in doc["recordings"]:
|
||||
source = self.root / relative_member(row["path"])
|
||||
if source.resolve() != source or source.stat().st_size != row["bytes"]:
|
||||
raise SessionIntegrityError("Canonical recording unavailable")
|
||||
with source.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != row["sha256"]:
|
||||
raise SessionIntegrityError("Canonical recording digest mismatch")
|
||||
key = row["session_id"]
|
||||
if key in self.rows:
|
||||
raise SessionIntegrityError("Ambiguous canonical recording")
|
||||
self.rows[key] = (source, row["sha256"])
|
||||
|
||||
def get(self, session_id: str) -> tuple[Path, str] | None:
|
||||
return self.rows.get(session_id)
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Worker-only LAB evidence API. New jobs use the installed-package executor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from k1link.compute.pipeline_telemetry import JsonlPipelineTelemetrySink
|
||||
from k1link.laboratory import (
|
||||
LaboratoryEvidenceRegistry,
|
||||
LaboratoryExecutionRegistry,
|
||||
LaboratoryRunner,
|
||||
)
|
||||
from k1link.laboratory.data_deletion import LOCK as DELETION_LOCK
|
||||
from k1link.laboratory.data_deletion import LabDeletionError, OwnedLabData
|
||||
from k1link.laboratory.deletion_inventory import inventory_worker
|
||||
from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority
|
||||
from k1link.laboratory.worker_gateway import LaboratoryGatewayConfiguration
|
||||
from k1link.laboratory.worker_recorded_sources import (
|
||||
WorkerCanonicalRecordings,
|
||||
WorkerRecordedSources,
|
||||
)
|
||||
from k1link.sessions.camera_frame import RecordedCameraFrameService
|
||||
from k1link.sessions.media import RecordedMediaInspector
|
||||
from k1link.web.lidar_api import build_lidar_router
|
||||
from k1link.web.lidar_local_surface_service import K1LocalSurfaceReadService
|
||||
from k1link.web.worker_laboratory_presentation import build_worker_laboratory_presentation
|
||||
from k1link.web.worker_laboratory_surface import build_worker_laboratory_router
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
authority = WorkerLaboratoryAuthority.from_environment()
|
||||
if authority is None:
|
||||
raise RuntimeError("LAB server requires a configured Worker runtime")
|
||||
root = authority.runtime_root
|
||||
config = Path(os.environ["MISSIONCORE_LAB_CONFIGURATION_ROOT"]).resolve(strict=True)
|
||||
credential = LaboratoryGatewayConfiguration(
|
||||
"http://127.0.0.1", Path(os.environ["MISSIONCORE_LAB_TOKEN_FILE"])
|
||||
)
|
||||
token = credential.token()
|
||||
registry = LaboratoryEvidenceRegistry.from_directory(config / "laboratories")
|
||||
execution = LaboratoryExecutionRegistry.from_file(
|
||||
config / "laboratory-execution.json", registry
|
||||
)
|
||||
runner = LaboratoryRunner(
|
||||
registry=execution,
|
||||
evidence_registry=registry,
|
||||
sink=JsonlPipelineTelemetrySink(root / "state" / "laboratory-runs.jsonl"),
|
||||
worker_authority=authority,
|
||||
)
|
||||
deletion_roots = json.loads(os.environ.get("MISSIONCORE_LAB_DELETION_ROOTS", "{}"))
|
||||
owned_data = OwnedLabData(root / "state" / "data-ownership", {
|
||||
name: Path(value) for name, value in deletion_roots.items()
|
||||
})
|
||||
camera = None
|
||||
ffmpeg = Path(os.environ.get("MISSIONCORE_LAB_FFMPEG", "/usr/bin/ffmpeg"))
|
||||
if (root / "recorded-sources" / "bindings.json").is_file() and ffmpeg.is_file():
|
||||
sources = WorkerRecordedSources(root / "recorded-sources")
|
||||
camera = RecordedCameraFrameService(
|
||||
None,
|
||||
RecordedMediaInspector(),
|
||||
ffmpeg_path=ffmpeg,
|
||||
cache_root=root / "presentation" / "camera-frame-cache",
|
||||
manifest_provider=sources.manifest,
|
||||
)
|
||||
surface_reader = K1LocalSurfaceReadService()
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
yield
|
||||
surface_reader.close()
|
||||
|
||||
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
||||
|
||||
@app.middleware("http")
|
||||
async def authorize(request: Request, call_next):
|
||||
if not hmac.compare_digest(request.headers.get("authorization", ""), "Bearer " + token):
|
||||
return JSONResponse({"detail": "Worker authentication required"}, status_code=401)
|
||||
if request.method not in {"GET", "HEAD"}:
|
||||
length = request.headers.get("content-length")
|
||||
if length is None or not length.isdecimal() or int(length) > 8 * 1024**2:
|
||||
return JSONResponse({"detail": "Bounded request body required"}, status_code=413)
|
||||
if (request.url.path != "/api/v1/laboratory/data-deletions"
|
||||
and shutil.disk_usage(root).free < 40 * 1024**3):
|
||||
return JSONResponse(
|
||||
{"detail": "Worker free-space reserve reached"}, status_code=507
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {
|
||||
"schema_version": "missioncore.laboratory-worker-health/v1",
|
||||
"role": "worker",
|
||||
"local_fallback": False,
|
||||
}
|
||||
|
||||
@app.post("/api/v1/laboratory/data-deletions")
|
||||
def delete_owned_data(value: DataDeletionRequest):
|
||||
try:
|
||||
with DELETION_LOCK:
|
||||
inventory_worker(owned_data, value.owner_ids)
|
||||
return owned_data.delete(value.owner_ids)
|
||||
except (LabDeletionError, OSError, ValueError) as exc:
|
||||
raise HTTPException(409, "Не удалось полностью удалить данные LAB на Worker.") from exc
|
||||
|
||||
app.include_router(
|
||||
build_worker_laboratory_router(
|
||||
repository_root=root,
|
||||
configuration_root=config,
|
||||
presentation_root=root / "presentation",
|
||||
ffmpeg_path=ffmpeg if ffmpeg.is_file() else None,
|
||||
camera_frame_provider=camera.extract if camera else None,
|
||||
camera_playback_provider=camera.playback_source if camera else None,
|
||||
evaluation_runner=runner,
|
||||
canonical_recording_provider=WorkerCanonicalRecordings(root / "recorded-sources").get,
|
||||
)
|
||||
)
|
||||
app.include_router(
|
||||
build_lidar_router(
|
||||
root_provider=lambda: (
|
||||
root / ".runtime" / "compute-experiments" / "lidar-replay-v2" / "packs"
|
||||
),
|
||||
ground_root_provider=lambda: (
|
||||
root / ".runtime" / "compute-experiments" / "lidar-ground-v1" / "benchmarks"
|
||||
),
|
||||
field_review_root_provider=lambda: (
|
||||
root / ".runtime" / "compute-experiments" / "lidar-field-review-v1" / "reviews"
|
||||
),
|
||||
local_surface_root_provider=lambda: (
|
||||
root / ".runtime" / "compute-experiments" / "k1-local-surface-v1" / "models"
|
||||
),
|
||||
e10_source_root_provider=lambda: (
|
||||
root / ".runtime" / "compute-experiments" / "e10" / "lidar-packs"
|
||||
),
|
||||
dataset_admission_provider=lambda: (
|
||||
root / ".runtime" / "dataset-gateway" / "admission.json"
|
||||
),
|
||||
dataset_preview_provider=lambda: root / ".runtime" / "dataset-gateway" / "preview.json",
|
||||
dataset_rellis_preview_provider=lambda: (
|
||||
root / ".runtime" / "dataset-gateway" / "rellis-preview.json"
|
||||
),
|
||||
dataset_rellis_admission_provider=lambda: (
|
||||
root / ".runtime" / "dataset-gateway" / "rellis-admission.json"
|
||||
),
|
||||
dataset_ground_preview_provider=lambda: (
|
||||
root / ".runtime" / "dataset-gateway" / "ground-comparison.json"
|
||||
),
|
||||
local_surface_read_service=surface_reader,
|
||||
)
|
||||
)
|
||||
if ffmpeg.is_file():
|
||||
app.include_router(build_worker_laboratory_presentation(root, ffmpeg))
|
||||
return app
|
||||
|
||||
|
||||
class DataDeletionRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
owner_ids: list[str] = Field(min_length=1, max_length=128)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Pinned shared segmentation assets, independent of historical LAB orchestration."""
|
||||
|
||||
from typing import Final
|
||||
|
||||
EOMT_ASSETS: Final[tuple[tuple[str, str, str, int], ...]] = (
|
||||
(
|
||||
"eomt-environment",
|
||||
"/environment",
|
||||
"8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0",
|
||||
211_776_082,
|
||||
),
|
||||
(
|
||||
"eomt-ffmpeg-runtime",
|
||||
"/opt/ffmpeg",
|
||||
"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69",
|
||||
256_208_352,
|
||||
),
|
||||
(
|
||||
"eomt-model-cache",
|
||||
"/cache",
|
||||
"064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c",
|
||||
2_552_355_458,
|
||||
),
|
||||
(
|
||||
"eomt-python-environment",
|
||||
"/opt/env",
|
||||
"b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20",
|
||||
5_120_848_705,
|
||||
),
|
||||
(
|
||||
"eomt-runner-bundle",
|
||||
"/runner",
|
||||
"0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7",
|
||||
145_141,
|
||||
),
|
||||
(
|
||||
"eomt-transformers-environment",
|
||||
"/opt/transformers",
|
||||
"f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9",
|
||||
225_272_284,
|
||||
),
|
||||
(
|
||||
"k1-valid-fov-root",
|
||||
"/valid-fov",
|
||||
"f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e",
|
||||
6_019,
|
||||
),
|
||||
)
|
||||
|
||||
DDRNET_ASSETS: Final[tuple[tuple[str, str, str, int], ...]] = (
|
||||
(
|
||||
"ddrnet-checkpoint",
|
||||
"/opt/nodedc/assets/ddrnet-checkpoint",
|
||||
"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6",
|
||||
259_419_077,
|
||||
),
|
||||
(
|
||||
"ddrnet-goose-mapping",
|
||||
"/opt/nodedc/assets/ddrnet-goose-mapping",
|
||||
"88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f",
|
||||
1_427,
|
||||
),
|
||||
(
|
||||
"ddrnet-goose-runner",
|
||||
"/opt/nodedc/assets/ddrnet-goose-runner",
|
||||
"b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1",
|
||||
32_877,
|
||||
),
|
||||
(
|
||||
"vegetation-policy",
|
||||
"/opt/nodedc/assets/vegetation-policy",
|
||||
"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35",
|
||||
3_022,
|
||||
),
|
||||
(
|
||||
"vegetation-provider-map",
|
||||
"/opt/nodedc/assets/vegetation-provider-map",
|
||||
"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352",
|
||||
2_756,
|
||||
),
|
||||
)
|
||||
|
||||
RUNTIME_ASSET_RELATIVE_PATHS: Final = {
|
||||
"eomt-environment": "derived\\perception-e3-opencv413092-v1",
|
||||
"eomt-ffmpeg-runtime": (
|
||||
"assets\\observatory-portable\\eomt-ffmpeg-runtime-frigate-8a364092b03561b9-v1"
|
||||
),
|
||||
"eomt-model-cache": ("assets\\observatory-portable\\eomt-model-cache-cityscapes-large-1024-v1"),
|
||||
"eomt-python-environment": "derived\\perception-p0-env-v1",
|
||||
"eomt-runner-bundle": "assets\\observatory-portable\\eomt-runner-bundle-v2",
|
||||
"eomt-transformers-environment": "derived\\perception-p0-transformers4576-v1",
|
||||
"k1-valid-fov-root": (
|
||||
"assets\\observatory-portable\\"
|
||||
"k1-valid-fov-root-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2-v1"
|
||||
),
|
||||
"ddrnet-checkpoint": (
|
||||
"assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-checkpoint.pth"
|
||||
),
|
||||
"ddrnet-goose-mapping": (
|
||||
"assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-goose-mapping.csv"
|
||||
),
|
||||
"ddrnet-goose-runner": (
|
||||
"assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-goose-runner.py"
|
||||
),
|
||||
"vegetation-policy": (
|
||||
"assets\\observatory-portable\\lab-v1-static-files-v1\\vegetation-policy.json"
|
||||
),
|
||||
"vegetation-provider-map": (
|
||||
"assets\\observatory-portable\\lab-v1-static-files-v1\\vegetation-provider-map.json"
|
||||
),
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -26,6 +26,8 @@ from k1link.laboratory.canonical_rerun_overlay import (
|
||||
canonical_lab_replay,
|
||||
canonical_recording_id,
|
||||
)
|
||||
from k1link.laboratory.local_presentations import LOCK as PRESENTATION_LOCK
|
||||
from k1link.laboratory.local_presentations import LocalPresentations
|
||||
from k1link.observatory.portable_object_replay import (
|
||||
RENDERER_VERSION as OBJECT_RENDERER_VERSION,
|
||||
)
|
||||
@@ -68,6 +70,7 @@ class PortableReplayService:
|
||||
media: RecordedMediaInspector,
|
||||
recording_source: Callable[[str], tuple[Path, str] | None],
|
||||
ffmpeg_path: Path,
|
||||
local_copies: LocalPresentations | None = None,
|
||||
) -> None:
|
||||
self.view = view
|
||||
self.data_dir = data_dir
|
||||
@@ -75,6 +78,7 @@ class PortableReplayService:
|
||||
self.recording_source = recording_source
|
||||
self.ffmpeg_path = ffmpeg_path
|
||||
self.cache = data_dir / "observatory-portable-replay-cache"
|
||||
self.local_copies = local_copies
|
||||
self._verified: OrderedDict[tuple[Path, str], tuple[int, ...]] = OrderedDict()
|
||||
|
||||
def _key(self, result_id: str, base_sha: str) -> tuple[str, dict[str, Any]]:
|
||||
@@ -132,12 +136,15 @@ class PortableReplayService:
|
||||
self._verified[fingerprint] = stamp
|
||||
while len(self._verified) > 32:
|
||||
self._verified.popitem(last=False)
|
||||
return CanonicalLabReplayArtifact(path, metadata["byte_length"], digest)
|
||||
artifact = CanonicalLabReplayArtifact(path, metadata["byte_length"], digest)
|
||||
if self.local_copies is not None:
|
||||
self.local_copies.register(result_id, artifact, sidecar)
|
||||
return artifact
|
||||
|
||||
def prepare(self, result_id: str, base_sha: str) -> CanonicalLabReplayArtifact:
|
||||
# Serialize packaging on the constrained operator host, including
|
||||
# concurrent clicks. Waiting readers cannot start a duplicate render.
|
||||
with _LOCK:
|
||||
with PRESENTATION_LOCK, _LOCK:
|
||||
cached = self.cached(result_id, base_sha)
|
||||
if cached is not None:
|
||||
return cached
|
||||
@@ -248,6 +255,8 @@ class PortableReplayService:
|
||||
staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, self.cache / f"{key}.json")
|
||||
if self.local_copies is not None:
|
||||
self.local_copies.register(result_id, artifact, self.cache / f"{key}.json")
|
||||
return artifact
|
||||
|
||||
def _composition_key(
|
||||
@@ -305,12 +314,15 @@ class PortableReplayService:
|
||||
self._verified[fingerprint] = stamp
|
||||
while len(self._verified) > 32:
|
||||
self._verified.popitem(last=False)
|
||||
return CanonicalLabReplayArtifact(path, metadata["byte_length"], digest)
|
||||
artifact = CanonicalLabReplayArtifact(path, metadata["byte_length"], digest)
|
||||
if self.local_copies is not None:
|
||||
self.local_copies.register(run_id, artifact, sidecar)
|
||||
return artifact
|
||||
|
||||
def prepare_composition(
|
||||
self, run_id: str, result_ids: tuple[str, ...], base_sha: str
|
||||
) -> CanonicalLabReplayArtifact:
|
||||
with _LOCK:
|
||||
with PRESENTATION_LOCK, _LOCK:
|
||||
cached = self.cached_composition(run_id, result_ids, base_sha)
|
||||
if cached is not None:
|
||||
return cached
|
||||
@@ -445,6 +457,8 @@ class PortableReplayService:
|
||||
staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, self.cache / f"{key}.json")
|
||||
if self.local_copies is not None:
|
||||
self.local_copies.register(run_id, artifact, self.cache / f"{key}.json")
|
||||
return artifact
|
||||
|
||||
def _camera(self, session_id: str, bundle: dict[str, Any]) -> RecordedMediaEpoch:
|
||||
|
||||
@@ -124,6 +124,10 @@ class PortableResultCache:
|
||||
or job.active_claimant_id is not None
|
||||
):
|
||||
return None
|
||||
if (
|
||||
self._sessions.data_dir / "lab-deletions" / "blocked" / (job.result_id + ".json")
|
||||
).exists():
|
||||
return None
|
||||
try:
|
||||
definition = self._definitions.resolve(job.setup_id, job.definition_sha256)
|
||||
recorded = definition.to_recorded_run_definition()
|
||||
|
||||
@@ -18,8 +18,8 @@ import json
|
||||
import re
|
||||
import stat
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path, PurePath, PurePosixPath
|
||||
from typing import cast
|
||||
|
||||
from k1link.artifact_gateway import (
|
||||
@@ -73,15 +73,14 @@ from k1link.sessions.models import (
|
||||
LabReplayCapability,
|
||||
LabSessionBinding,
|
||||
SessionIntegrityError,
|
||||
SessionNotFoundError,
|
||||
SessionSummary,
|
||||
)
|
||||
from k1link.sessions.store import SessionStore
|
||||
|
||||
_COPY_CHUNK_BYTES = 1024 * 1024
|
||||
_FULL_ROUTE_LABEL = "полный маршрут и воспроизведение"
|
||||
_LEGACY_CANONICAL_RESULT = re.compile(
|
||||
r"^lab-v1-vegetation-shadow-[a-f0-9]{64}$"
|
||||
)
|
||||
_LEGACY_CANONICAL_RESULT = re.compile(r"^lab-v1-vegetation-shadow-[a-f0-9]{64}$")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -135,10 +134,9 @@ class PortableObservatoryResultPublisher:
|
||||
"portable result package content address disagrees with queue success"
|
||||
)
|
||||
source_summary = self._verify_source(job, definition)
|
||||
artifact_paths = _verify_package_artifacts(root, package.artifacts)
|
||||
result_document = _read_canonical_result_document(
|
||||
artifact_paths[RESULT_DOCUMENT_ROLE]
|
||||
)
|
||||
archived_paths = self._retired_artifact_paths(root, package, job)
|
||||
artifact_paths = _verify_package_artifacts(root, package.artifacts, archived_paths)
|
||||
result_document = _read_canonical_result_document(artifact_paths[RESULT_DOCUMENT_ROLE])
|
||||
context = PortableResultValidationContext(
|
||||
manifest=package,
|
||||
job=job,
|
||||
@@ -155,6 +153,12 @@ class PortableObservatoryResultPublisher:
|
||||
"portable result document failed its exact contract validator"
|
||||
) from exc
|
||||
|
||||
existing = self._existing_publication(job, definition, package, profile)
|
||||
if existing is not None:
|
||||
binding, artifact_manifest = existing
|
||||
self._retire_transport(root, package, job, artifact_manifest)
|
||||
return PublishedPortableObservatoryResult(binding, package, artifact_manifest)
|
||||
|
||||
artifact_manifest = self._archive_package(
|
||||
job=job,
|
||||
package=package,
|
||||
@@ -197,22 +201,266 @@ class PortableObservatoryResultPublisher:
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"portable result could not be projected as immutable LAB provenance"
|
||||
) from exc
|
||||
# Catalog and immutable archive are durable before transfer duplicates go away.
|
||||
# The receipt is written first so an interrupted cleanup remains retryable.
|
||||
self._retire_transport(root, package, job, artifact_manifest)
|
||||
return PublishedPortableObservatoryResult(
|
||||
binding=binding,
|
||||
package=package,
|
||||
artifact_manifest=artifact_manifest,
|
||||
)
|
||||
|
||||
def retire_published_transport(
|
||||
self, *, job: ObservatoryRecordedJob, package_root: Path
|
||||
) -> PublishedPortableObservatoryResult:
|
||||
"""Close an already published transfer, without re-admitting old compute.
|
||||
|
||||
Historical result ownership comes from its immutable catalog and archive.
|
||||
This method cannot publish a result or add an obsolete definition to the
|
||||
execution allowlist. Every retained payload is verified before deletion.
|
||||
"""
|
||||
_verify_terminal_job(job)
|
||||
if job.publication_state != "published":
|
||||
raise PortableResultPublicationBlockedError("result is not durably published")
|
||||
root, _, package = _read_package(package_root)
|
||||
try:
|
||||
binding = self._session_store.get_lab_instance(cast(str, job.result_id))
|
||||
if binding is None:
|
||||
raise ValueError("published result binding is missing")
|
||||
provenance = binding.provenance
|
||||
stored_package = provenance["result_package"]
|
||||
manifest = self._artifact_store.read_manifest(stored_package["artifact_manifest_id"])
|
||||
definition_identity = dict(package.run_definition)
|
||||
definition_sha = definition_identity.pop("definition_sha256")
|
||||
profile = provenance["calculation_profile"]
|
||||
result_document = next(a for a in package.artifacts if a.role == RESULT_DOCUMENT_ROLE)
|
||||
expected_package = {
|
||||
"schema_version": PORTABLE_RESULT_PACKAGE_SCHEMA,
|
||||
"manifest_sha256": package.manifest_sha256,
|
||||
"identity_sha256": package.identity_sha256,
|
||||
"artifact_manifest_id": manifest.manifest_id,
|
||||
"result_document_sha256": result_document.sha256,
|
||||
"artifacts": [a.as_dict() for a in package.artifacts],
|
||||
}
|
||||
if (
|
||||
root.name != job.result_sha256
|
||||
or package.manifest_sha256 != job.result_sha256
|
||||
or package.job != job_identity_document(job)
|
||||
or package.source != source_identity_document(job)
|
||||
or definition_sha != job.definition_sha256
|
||||
or canonical_sha256(definition_identity) != job.definition_sha256
|
||||
or package.result["result_id"] != job.result_id
|
||||
or binding.session_id != job.result_id
|
||||
or binding.result_id != job.result_id
|
||||
or binding.source_session_id != job.source_session_id
|
||||
or binding.source_result_id is not None
|
||||
or binding.config_sha256 != job.definition_sha256
|
||||
or binding.result_kind != package.result["result_kind"]
|
||||
or provenance["schema_version"] != PORTABLE_RESULT_PUBLICATION_SCHEMA
|
||||
or provenance["authority"] != OBSERVATION_ONLY_AUTHORITY
|
||||
or provenance["job"] != package.job
|
||||
or provenance["source"] != package.source
|
||||
or provenance["run_definition"] != package.run_definition
|
||||
or stored_package != expected_package
|
||||
or profile["definition_sha256"] != job.definition_sha256
|
||||
or provenance["calculation_profile_sha256"] != canonical_sha256(profile)
|
||||
or manifest.metadata.get("calculation-profile-sha256") != canonical_sha256(profile)
|
||||
or manifest.metadata.get("result-contract-sha256")
|
||||
!= package.result["result_contract_sha256"]
|
||||
or binding.replay_capability is None
|
||||
or provenance["replay_capability"] != binding.replay_capability.as_dict()
|
||||
):
|
||||
raise ValueError("published transfer identities differ")
|
||||
self._archived_artifact_paths(package, job, manifest)
|
||||
fallback = self._retired_artifact_paths(root, package, job)
|
||||
_verify_package_artifacts(root, package.artifacts, fallback)
|
||||
except (
|
||||
ArtifactGatewayError,
|
||||
SessionNotFoundError,
|
||||
OSError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
ValueError,
|
||||
) as exc:
|
||||
raise PortableResultPackageIntegrityError("published transfer is not verified") from exc
|
||||
self._retire_transport(root, package, job, manifest)
|
||||
return PublishedPortableObservatoryResult(binding, package, manifest)
|
||||
|
||||
def _existing_publication(
|
||||
self,
|
||||
job: ObservatoryRecordedJob,
|
||||
definition: PortableRunDefinition,
|
||||
package: PortableResultPackageManifest,
|
||||
profile: PortableCalculationProfilePolicy,
|
||||
) -> tuple[LabSessionBinding, ArtifactManifest] | None:
|
||||
# Queue updated_at changes when publication is acknowledged. Neither that
|
||||
# timestamp nor a later UI label may rewrite immutable published provenance.
|
||||
try:
|
||||
summary = self._session_store.get_session(cast(str, job.result_id)).summary
|
||||
except SessionNotFoundError:
|
||||
return None
|
||||
binding = summary.lab
|
||||
if binding is None:
|
||||
raise PortableResultPackageIntegrityError("result id belongs to a source recording")
|
||||
try:
|
||||
published_profile = binding.provenance["calculation_profile"]
|
||||
archived_profile = replace(profile, display_name=published_profile["display_name"])
|
||||
manifest = self._artifact_store.read_manifest(
|
||||
binding.provenance["result_package"]["artifact_manifest_id"]
|
||||
)
|
||||
expected_replay = LabReplayCapability(
|
||||
schema_version="missioncore.observation-lab-replay-capability/v2",
|
||||
kind="portable-result-review",
|
||||
viewer_profile="portable-result",
|
||||
timeline="result-defined",
|
||||
activation="explicit",
|
||||
commands_enabled=False,
|
||||
)
|
||||
expected = _publication_provenance(
|
||||
job=job,
|
||||
definition=definition,
|
||||
package=package,
|
||||
artifact_manifest=manifest,
|
||||
profile=archived_profile,
|
||||
replay_capability=expected_replay,
|
||||
)
|
||||
if (
|
||||
binding.session_id != job.result_id
|
||||
or binding.result_id != job.result_id
|
||||
or binding.source_session_id != job.source_session_id
|
||||
or binding.source_result_id is not None
|
||||
or binding.config_sha256 != definition.definition_sha256
|
||||
or binding.lab_id != profile.lab_id
|
||||
or binding.result_kind != definition.result_contract.result_kind
|
||||
or binding.replay_capability != expected_replay
|
||||
or binding.provenance != expected
|
||||
or manifest.metadata.get("calculation-profile-sha256")
|
||||
!= archived_profile.identity_sha256
|
||||
or manifest.metadata.get("result-contract-sha256")
|
||||
!= definition.result_contract.contract_sha256
|
||||
):
|
||||
raise PortableResultPackageIntegrityError("existing publication identity differs")
|
||||
self._archived_artifact_paths(package, job, manifest)
|
||||
return binding, manifest
|
||||
except (ArtifactGatewayError, OSError, KeyError, TypeError, ValueError) as exc:
|
||||
raise PortableResultPackageIntegrityError("existing publication is invalid") from exc
|
||||
|
||||
def _retired_artifact_paths(
|
||||
self,
|
||||
root: Path,
|
||||
package: PortableResultPackageManifest,
|
||||
job: ObservatoryRecordedJob,
|
||||
) -> dict[str, Path]:
|
||||
receipt = root / "retired-transport.json"
|
||||
if not receipt.exists() and not receipt.is_symlink():
|
||||
return {}
|
||||
path = _resolve_local_member(root, PurePosixPath(receipt.name))
|
||||
if path.stat().st_size > 4096:
|
||||
raise PortableResultPackageIntegrityError("transport retirement receipt is too large")
|
||||
try:
|
||||
document = json.loads(path.read_bytes())
|
||||
manifest_id = document["artifact_manifest_id"]
|
||||
expected = _retirement_receipt(package, job, manifest_id)
|
||||
if document != expected or path.read_bytes() != canonical_json(expected):
|
||||
raise ValueError("retirement identity differs")
|
||||
manifest = self._artifact_store.read_manifest(manifest_id)
|
||||
return self._archived_artifact_paths(package, job, manifest)
|
||||
except (ArtifactGatewayError, OSError, ValueError, KeyError, TypeError) as exc:
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"transport archive receipt is invalid"
|
||||
) from exc
|
||||
|
||||
def _archived_artifact_paths(
|
||||
self,
|
||||
package: PortableResultPackageManifest,
|
||||
job: ObservatoryRecordedJob,
|
||||
manifest: ArtifactManifest,
|
||||
) -> dict[str, Path]:
|
||||
expected = {
|
||||
"package-sha256": package.manifest_sha256,
|
||||
"package-identity-sha256": package.identity_sha256,
|
||||
"job-id": job.job_id,
|
||||
"job-identity-sha256": job.identity_sha256,
|
||||
"definition-sha256": job.definition_sha256,
|
||||
"source-bundle-sha256": job.source_bundle_sha256,
|
||||
}
|
||||
if (
|
||||
manifest.artifact_type != "observatory-portable-result"
|
||||
or manifest.subject_id != job.result_id
|
||||
or any(manifest.metadata.get(k) != v for k, v in expected.items())
|
||||
):
|
||||
raise PortableResultPackageIntegrityError("transport archive identity differs")
|
||||
paths = {}
|
||||
members = [(a.role, a.sha256, a.byte_length) for a in package.artifacts]
|
||||
members.append(
|
||||
(RESULT_PACKAGE_MANIFEST_ROLE, package.manifest_sha256, len(package.canonical_bytes))
|
||||
)
|
||||
for role, digest, size in members:
|
||||
member = manifest.member(role)
|
||||
if (member.sha256, member.byte_length) != (digest, size):
|
||||
raise PortableResultPackageIntegrityError("transport archive member differs")
|
||||
path = self._artifact_store.object_path(digest)
|
||||
path = _resolve_local_member(
|
||||
self._artifact_store.root, path.relative_to(self._artifact_store.root)
|
||||
)
|
||||
if _hash_file(path) != (digest, size):
|
||||
raise PortableResultPackageIntegrityError("transport archive payload differs")
|
||||
paths[role] = path
|
||||
return paths
|
||||
|
||||
def _retire_transport(
|
||||
self,
|
||||
root: Path,
|
||||
package: PortableResultPackageManifest,
|
||||
job: ObservatoryRecordedJob,
|
||||
manifest: ArtifactManifest,
|
||||
) -> None:
|
||||
# No recursive sweep: only this package's verified, non-shared transfer files.
|
||||
from .portable_artifact_transport import _write_immutable_file
|
||||
|
||||
try:
|
||||
self._archived_artifact_paths(package, job, manifest)
|
||||
_write_immutable_file(
|
||||
root / "retired-transport.json",
|
||||
canonical_json(_retirement_receipt(package, job, manifest.manifest_id)),
|
||||
)
|
||||
for artifact in package.artifacts:
|
||||
path = root / artifact.relative_path
|
||||
if not path.exists() and not path.is_symlink():
|
||||
continue
|
||||
path = _resolve_package_member(root, artifact.relative_path)
|
||||
before = path.stat()
|
||||
if before.st_nlink != 1 or _hash_file(path) != (
|
||||
artifact.sha256,
|
||||
artifact.byte_length,
|
||||
):
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"changed/shared staging file preserved"
|
||||
)
|
||||
if path.stat() != before:
|
||||
raise PortableResultPackageIntegrityError("staging changed during retirement")
|
||||
path.unlink()
|
||||
# Keep manifest/binding/receipt and directories for exact retries.
|
||||
import os
|
||||
|
||||
fd = os.open(path.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
except (ArtifactGatewayError, OSError, ValueError) as exc:
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"transport retirement incomplete; retry safely"
|
||||
) from exc
|
||||
|
||||
def _verify_source(
|
||||
self,
|
||||
job: ObservatoryRecordedJob,
|
||||
definition: PortableRunDefinition,
|
||||
) -> SessionSummary:
|
||||
try:
|
||||
detail, catalog_sha256 = (
|
||||
self._session_store.get_session_with_catalog_snapshot(
|
||||
job.source_session_id
|
||||
)
|
||||
detail, catalog_sha256 = self._session_store.get_session_with_catalog_snapshot(
|
||||
job.source_session_id
|
||||
)
|
||||
except Exception as exc:
|
||||
raise PortableResultPackageIntegrityError(
|
||||
@@ -371,8 +619,7 @@ def resolve_published_portable_calculation_profile(
|
||||
or binding.result_kind != definition.result_contract.result_kind
|
||||
or binding.replay_capability is None
|
||||
or binding.replay_capability.kind != "portable-result-review"
|
||||
or provenance["replay_capability"]
|
||||
!= binding.replay_capability.as_dict()
|
||||
or provenance["replay_capability"] != binding.replay_capability.as_dict()
|
||||
):
|
||||
return None
|
||||
return profile.as_dict()
|
||||
@@ -491,9 +738,7 @@ def _read_package(
|
||||
)
|
||||
package = PortableResultPackageManifest.from_bytes(payload)
|
||||
if hashlib.sha256(payload).hexdigest() != package.manifest_sha256:
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"portable result package manifest digest changed"
|
||||
)
|
||||
raise PortableResultPackageIntegrityError("portable result package manifest digest changed")
|
||||
return root, manifest_path, package
|
||||
|
||||
|
||||
@@ -520,9 +765,7 @@ def _verify_package_identity(
|
||||
"portable result package violates its sealed result contract"
|
||||
)
|
||||
if package.authority != definition.authority.as_dict():
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"portable result package authority changed"
|
||||
)
|
||||
raise PortableResultPackageIntegrityError("portable result package authority changed")
|
||||
|
||||
|
||||
def _verify_source_documents(
|
||||
@@ -539,9 +782,7 @@ def _verify_source_documents(
|
||||
"admitted portable source documents are unavailable"
|
||||
) from exc
|
||||
if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode):
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"portable source document root is unsafe"
|
||||
)
|
||||
raise PortableResultPackageIntegrityError("portable source document root is unsafe")
|
||||
bundle = _read_content_addressed_document(root, job.source_bundle_sha256)
|
||||
capability = _read_content_addressed_document(
|
||||
root,
|
||||
@@ -638,10 +879,21 @@ def _read_content_addressed_document(root: Path, document_sha256: str) -> dict[s
|
||||
def _verify_package_artifacts(
|
||||
root: Path,
|
||||
artifacts: Sequence[PortableResultArtifact],
|
||||
archived_paths: Mapping[str, Path] | None = None,
|
||||
) -> dict[str, Path]:
|
||||
resolved: dict[str, Path] = {}
|
||||
for artifact in artifacts:
|
||||
path = _resolve_package_member(root, artifact.relative_path)
|
||||
candidate = root / artifact.relative_path
|
||||
if not candidate.exists() and not candidate.is_symlink() and archived_paths:
|
||||
# An archive receipt never excuses an unsafe parent or a corrupt existing file.
|
||||
current = candidate.parent
|
||||
while current != root:
|
||||
if current.is_symlink():
|
||||
raise PortableResultPackageIntegrityError("staging parent is a symlink")
|
||||
current = current.parent
|
||||
path = archived_paths[artifact.role]
|
||||
else:
|
||||
path = _resolve_package_member(root, artifact.relative_path)
|
||||
digest, byte_length = _hash_file(path)
|
||||
if digest != artifact.sha256 or byte_length != artifact.byte_length:
|
||||
raise PortableResultPackageIntegrityError(
|
||||
@@ -652,7 +904,10 @@ def _verify_package_artifacts(
|
||||
|
||||
|
||||
def _resolve_package_member(root: Path, relative_path: str) -> Path:
|
||||
portable = relative_artifact_path(relative_path)
|
||||
return _resolve_local_member(root, relative_artifact_path(relative_path))
|
||||
|
||||
|
||||
def _resolve_local_member(root: Path, portable: PurePath) -> Path:
|
||||
candidate = root.joinpath(*portable.parts)
|
||||
current = root
|
||||
try:
|
||||
@@ -672,9 +927,7 @@ def _resolve_package_member(root: Path, relative_path: str) -> Path:
|
||||
"portable result artifact is unavailable"
|
||||
) from exc
|
||||
if not resolved.is_relative_to(root) or not stat.S_ISREG(metadata.st_mode):
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"portable result artifact escapes its package"
|
||||
)
|
||||
raise PortableResultPackageIntegrityError("portable result artifact escapes its package")
|
||||
return resolved
|
||||
|
||||
|
||||
@@ -688,9 +941,7 @@ def _read_canonical_result_document(path: Path) -> dict[str, object]:
|
||||
) from exc
|
||||
document = object_document(decoded, "portable result document")
|
||||
if payload != canonical_json(document):
|
||||
raise PortableResultPackageIntegrityError(
|
||||
"portable result document is not canonical JSON"
|
||||
)
|
||||
raise PortableResultPackageIntegrityError("portable result document is not canonical JSON")
|
||||
return document
|
||||
|
||||
|
||||
@@ -709,10 +960,7 @@ def _publish_exact_member(
|
||||
raise PortableResultPackageIntegrityError(
|
||||
f"portable result artifact could not be archived: {role}"
|
||||
) from exc
|
||||
if (
|
||||
published.sha256 != expected_sha256
|
||||
or published.byte_length != expected_byte_length
|
||||
):
|
||||
if published.sha256 != expected_sha256 or published.byte_length != expected_byte_length:
|
||||
raise PortableResultPackageIntegrityError(
|
||||
f"portable result artifact changed while it was archived: {role}"
|
||||
)
|
||||
@@ -828,3 +1076,15 @@ def _hash_file(path: Path) -> tuple[str, int]:
|
||||
"portable result artifact could not be read"
|
||||
) from exc
|
||||
return digest.hexdigest(), byte_length
|
||||
|
||||
|
||||
def _retirement_receipt(
|
||||
package: PortableResultPackageManifest, job: ObservatoryRecordedJob, manifest_id: str
|
||||
) -> dict[str, object]:
|
||||
return {
|
||||
"schema_version": "missioncore.observatory-transport-retirement/v1",
|
||||
"job_id": job.job_id,
|
||||
"job_identity_sha256": job.identity_sha256,
|
||||
"package_sha256": package.manifest_sha256,
|
||||
"artifact_manifest_id": manifest_id,
|
||||
}
|
||||
|
||||
@@ -30,6 +30,8 @@ class PortableResultViewService:
|
||||
def read(self, result_id: str) -> dict[str, object]:
|
||||
if _RESULT_ID.fullmatch(result_id) is None:
|
||||
raise ValueError("portable result id is invalid")
|
||||
if (self.sessions.data_dir / "lab-deletions" / "blocked" / (result_id + ".json")).exists():
|
||||
raise PortableResultViewError("LAB deletion is in progress or complete")
|
||||
try:
|
||||
binding = self.sessions.get_lab_instance(result_id)
|
||||
except SessionNotFoundError as exc:
|
||||
@@ -50,8 +52,7 @@ class PortableResultViewService:
|
||||
if (
|
||||
provenance.get("schema_version")
|
||||
!= "missioncore.observatory-portable-result-publication/v1"
|
||||
or provenance.get("replay_capability")
|
||||
!= binding.replay_capability.as_dict()
|
||||
or provenance.get("replay_capability") != binding.replay_capability.as_dict()
|
||||
or not isinstance(package, dict)
|
||||
or not isinstance(source, dict)
|
||||
or source.get("session_id") != binding.source_session_id
|
||||
@@ -81,8 +82,7 @@ class PortableResultViewService:
|
||||
or manifest.subject_id != result_id
|
||||
or manifest.manifest_id != manifest_id
|
||||
or manifest.metadata.get("package-sha256") != package_sha256
|
||||
or package.get("schema_version")
|
||||
!= "missioncore.observatory-portable-result-package/v1"
|
||||
or package.get("schema_version") != "missioncore.observatory-portable-result-package/v1"
|
||||
or package.get("result_document_sha256") != member.sha256
|
||||
or member.media_type != "application/json"
|
||||
or not 0 < member.byte_length <= _MAX_RESULT_DOCUMENT_BYTES
|
||||
|
||||
@@ -23,7 +23,7 @@ import os
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections.abc import Callable, Iterator
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from contextlib import contextmanager, suppress
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
@@ -97,6 +97,11 @@ _AUTHORITY: Final = {
|
||||
}
|
||||
|
||||
_SCHEMA_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS observatory_hidden_job_projections (
|
||||
job_id TEXT PRIMARY KEY REFERENCES observatory_recorded_jobs(job_id),
|
||||
hidden_at_utc TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS simulation_worker_reservation (
|
||||
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
||||
owner_id TEXT NOT NULL,
|
||||
@@ -2203,6 +2208,25 @@ class ObservatoryRecordedJobQueue:
|
||||
with self._read_connection() as connection:
|
||||
return self._get_job(connection, job_id)
|
||||
|
||||
def has_source_consumers(self, session_ids: Sequence[str]) -> bool:
|
||||
"""Full durable queue query, including hidden/pending/paused consumers."""
|
||||
if not session_ids:
|
||||
return True
|
||||
with self._read_connection() as connection:
|
||||
for session_id in session_ids:
|
||||
_validate_pattern(session_id, _SESSION_ID, "source session id")
|
||||
if (
|
||||
connection.execute(
|
||||
"SELECT 1 FROM observatory_recorded_jobs WHERE source_session_id = ? "
|
||||
"AND (state NOT IN ('succeeded', 'failed') "
|
||||
"OR publication_state IN ('pending', 'failed')) LIMIT 1",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
is not None
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_by_idempotency_key(self, idempotency_key: str) -> ObservatoryRecordedJob:
|
||||
_validate_pattern(idempotency_key, _IDEMPOTENCY_KEY, "idempotency key")
|
||||
with self._read_connection() as connection:
|
||||
@@ -2216,6 +2240,36 @@ class ObservatoryRecordedJobQueue:
|
||||
)
|
||||
return _job_from_row(row)
|
||||
|
||||
def hide_deleted_projection(self, job_id: str) -> None:
|
||||
"""Finalize a confirmed storage deletion; retain only the bounded job ledger."""
|
||||
_validate_pattern(job_id, _JOB_ID, "job id")
|
||||
with self._transaction() as connection:
|
||||
job = self._get_job(connection, job_id)
|
||||
if job.state not in {"failed", "succeeded"}:
|
||||
raise ObservatoryRecordedQueueConflictError("active work cannot be deleted")
|
||||
connection.execute(
|
||||
"INSERT OR IGNORE INTO observatory_hidden_job_projections VALUES (?, ?)",
|
||||
(job_id, self._clock()),
|
||||
)
|
||||
|
||||
def hide_failed_projection(self, job_id: str) -> None:
|
||||
"""Remove a failed attempt from operator history, retaining the audit ledger.
|
||||
|
||||
Successful results and active work cannot be hidden through this action.
|
||||
Worker scratch retirement is separate and must verify ownership first.
|
||||
"""
|
||||
_validate_pattern(job_id, _JOB_ID, "job id")
|
||||
with self._transaction() as connection:
|
||||
job = self._get_job(connection, job_id)
|
||||
if job.state != "failed" or job.result_id is not None:
|
||||
raise ObservatoryRecordedQueueConflictError(
|
||||
"only failed attempts without a result can be removed from history"
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT OR IGNORE INTO observatory_hidden_job_projections VALUES (?, ?)",
|
||||
(job_id, self._clock()),
|
||||
)
|
||||
|
||||
def list_jobs(
|
||||
self,
|
||||
*,
|
||||
@@ -2223,6 +2277,7 @@ class ObservatoryRecordedJobQueue:
|
||||
setup_id: str | None = None,
|
||||
definition_sha256: str | None = None,
|
||||
limit: int = 100,
|
||||
include_hidden: bool = True,
|
||||
) -> tuple[ObservatoryRecordedJob, ...]:
|
||||
if source_session_id is not None:
|
||||
_validate_pattern(source_session_id, _SESSION_ID, "source session id")
|
||||
@@ -2233,6 +2288,8 @@ class ObservatoryRecordedJobQueue:
|
||||
if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 500:
|
||||
raise ValueError("recorded-job list limit is invalid")
|
||||
clauses: list[str] = []
|
||||
if not include_hidden:
|
||||
clauses.append("job_id NOT IN (SELECT job_id FROM observatory_hidden_job_projections)")
|
||||
parameters: list[object] = []
|
||||
if source_session_id is not None:
|
||||
clauses.append("source_session_id = ?")
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Retire only registered, reproducible source transport copies after use.
|
||||
|
||||
No TTL, model roots, source deletion, or discovery-based blanket cleanup.
|
||||
Reader locks span HTTP responses. Durable queue references protect pending work.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tempfile
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from .recorded_jobs import ObservatoryRecordedQueueError
|
||||
from .transfer_space import locked_file, secure_directory
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceCopy:
|
||||
path: Path
|
||||
sha256: str
|
||||
byte_length: int
|
||||
|
||||
def document(self) -> dict[str, object]:
|
||||
return {"path": str(self.path.absolute()), "sha256": self.sha256, "bytes": self.byte_length}
|
||||
|
||||
|
||||
def _verify(row: dict[str, Any]) -> None:
|
||||
path = Path(row["path"])
|
||||
if not path.is_absolute() or path.resolve() != path:
|
||||
raise ValueError("Noncanonical source copy")
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
try:
|
||||
before = os.fstat(fd)
|
||||
if not stat.S_ISREG(before.st_mode) or before.st_size != row["bytes"]:
|
||||
raise ValueError("Source copy length/type changed")
|
||||
digest = hashlib.sha256()
|
||||
while chunk := os.read(fd, 1024 * 1024):
|
||||
digest.update(chunk)
|
||||
after = os.fstat(fd)
|
||||
current = path.stat(follow_symlinks=False)
|
||||
if (
|
||||
(before.st_ino, before.st_size, before.st_mtime_ns)
|
||||
!= (
|
||||
after.st_ino,
|
||||
after.st_size,
|
||||
after.st_mtime_ns,
|
||||
)
|
||||
or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
|
||||
!= (current.st_dev, current.st_ino, current.st_size, current.st_mtime_ns)
|
||||
or digest.hexdigest() != row["sha256"]
|
||||
):
|
||||
raise ValueError("Source copy identity changed")
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _save(path: Path, row: dict[str, Any]) -> None:
|
||||
fd, name = tempfile.mkstemp(prefix=".pending-", dir=path.parent)
|
||||
temporary = Path(name)
|
||||
try:
|
||||
if os.fstat(fd).st_nlink != 1:
|
||||
raise ValueError("Unsafe source ledger")
|
||||
with os.fdopen(fd, "wb", closefd=False) as stream:
|
||||
stream.write(json.dumps(row, sort_keys=True).encode())
|
||||
stream.flush()
|
||||
os.fsync(fd)
|
||||
os.replace(temporary, path)
|
||||
directory = os.open(path.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
os.close(fd)
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
class SourceTransportLifecycle:
|
||||
def __init__(self, root: Path, has_consumers: Callable[[Sequence[str]], bool]) -> None:
|
||||
self.root = secure_directory(root)
|
||||
self.ledger = secure_directory(root / ".lifecycle")
|
||||
self.has_consumers = has_consumers
|
||||
self._cursor = ""
|
||||
|
||||
def acquire_reader(self) -> int:
|
||||
import fcntl
|
||||
|
||||
return locked_file(self.ledger / ".readers", fcntl.LOCK_SH)
|
||||
|
||||
@contextmanager
|
||||
def reading(self) -> Iterator[None]:
|
||||
fd = self.acquire_reader()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def register(self, copy: SourceCopy, *, sources: Sequence[SourceCopy], session_id: str) -> None:
|
||||
"""Called under reading(), exclusively for server-admitted producer files."""
|
||||
import fcntl
|
||||
|
||||
relative = copy.path.relative_to(self.root)
|
||||
if relative.parts[0] == ".lifecycle" or not sources:
|
||||
raise ValueError("Invalid source copy ownership")
|
||||
key = hashlib.sha256(str(relative).encode()).hexdigest()
|
||||
path = self.ledger / f"{key}.json"
|
||||
fd = locked_file(self.ledger / ".metadata", fcntl.LOCK_EX)
|
||||
try:
|
||||
previous = self._load(path) if path.exists() else {}
|
||||
if previous and previous["copy"] != copy.document():
|
||||
raise ValueError("Source copy ledger identity conflict")
|
||||
sessions = sorted(set(previous.get("sessions", [])) | {session_id})
|
||||
_save(
|
||||
path,
|
||||
{
|
||||
"version": 1,
|
||||
"state": "active",
|
||||
"copy": copy.document(),
|
||||
"sources": [source.document() for source in sources],
|
||||
"sessions": sessions,
|
||||
},
|
||||
)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def _load(self, path: Path) -> dict[str, Any]:
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size > 16 * 1024 * 1024:
|
||||
raise ValueError("Unsafe source ledger")
|
||||
row = json.loads(path.read_bytes())
|
||||
if not isinstance(row, dict):
|
||||
raise ValueError("Invalid source ledger")
|
||||
target = Path(row["copy"]["path"])
|
||||
relative = target.relative_to(self.root)
|
||||
expected = hashlib.sha256(str(relative).encode()).hexdigest() + ".json"
|
||||
if row["version"] != 1 or path.name != expected or relative.parts[0] == ".lifecycle":
|
||||
raise ValueError("Invalid source ledger identity")
|
||||
if (
|
||||
not row["sources"]
|
||||
or not row["sessions"]
|
||||
or row["state"] not in {"active", "retiring", "retired"}
|
||||
):
|
||||
raise ValueError("Incomplete source ownership")
|
||||
return cast(dict[str, Any], row)
|
||||
|
||||
def collect(
|
||||
self, *, limit: int = 8, only_paths: Sequence[Path] | None = None
|
||||
) -> dict[str, int]:
|
||||
import fcntl
|
||||
|
||||
if not 1 <= limit <= 128:
|
||||
raise ValueError("Invalid collection bound")
|
||||
allowed = None if only_paths is None else frozenset(only_paths)
|
||||
if allowed is not None and any(
|
||||
not p.is_absolute() or not p.is_relative_to(self.root) or p.resolve() != p
|
||||
for p in allowed
|
||||
):
|
||||
raise ValueError("Invalid explicit collection scope")
|
||||
report = {"retired": 0, "bytes": 0, "protected": 0, "unverified": 0, "reading": 0}
|
||||
try:
|
||||
fd = locked_file(self.ledger / ".readers", fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
report["reading"] = 1
|
||||
return report
|
||||
try:
|
||||
if allowed is None:
|
||||
paths = sorted(self.ledger.glob("*.json"))
|
||||
else:
|
||||
paths = sorted(
|
||||
self.ledger
|
||||
/ (hashlib.sha256(str(p.relative_to(self.root)).encode()).hexdigest() + ".json")
|
||||
for p in allowed
|
||||
)
|
||||
ordered = [p for p in paths if p.name > self._cursor] + [
|
||||
p for p in paths if p.name <= self._cursor
|
||||
]
|
||||
for path in ordered[:limit]:
|
||||
self._cursor = path.name
|
||||
try:
|
||||
row = self._load(path)
|
||||
if row["state"] == "retired":
|
||||
continue
|
||||
if self.has_consumers(row["sessions"]):
|
||||
report["protected"] += 1
|
||||
continue
|
||||
target = Path(row["copy"]["path"])
|
||||
if allowed is not None and target not in allowed:
|
||||
raise ValueError("Copy is outside explicit collection scope")
|
||||
# Missing/changed originals preserve the duplicate for recovery.
|
||||
for source in row["sources"]:
|
||||
original = Path(source["path"])
|
||||
if original.is_relative_to(self.root):
|
||||
raise ValueError("Another transfer copy is not an original")
|
||||
_verify(source)
|
||||
if target.exists() or target.is_symlink():
|
||||
_verify(row["copy"])
|
||||
if target.stat().st_nlink != 1:
|
||||
raise ValueError("Shared filesystem owner")
|
||||
row["state"] = "retiring"
|
||||
_save(path, row)
|
||||
target.unlink()
|
||||
directory = os.open(target.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
report["bytes"] += row["copy"]["bytes"]
|
||||
row["state"] = "retired"
|
||||
_save(path, row)
|
||||
report["retired"] += 1
|
||||
except (OSError, ValueError, KeyError, TypeError, ObservatoryRecordedQueueError):
|
||||
report["unverified"] += 1
|
||||
return report
|
||||
finally:
|
||||
os.close(fd)
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Physical disk admission for transfers, independent of model/LAB complexity.
|
||||
|
||||
One ledger coordinates input and result writers on the same device. Kernel
|
||||
locks own reservations: process death releases capacity, never payload files.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import uuid
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.cache_budget import FREE_RESERVE
|
||||
|
||||
|
||||
class TransferCapacityError(ValueError):
|
||||
"""A retryable storage shortage, not an invalid model or result."""
|
||||
|
||||
|
||||
def secure_directory(path: Path) -> Path:
|
||||
path = path.absolute()
|
||||
if path.resolve() != path:
|
||||
raise ValueError("Transfer directory is not canonical")
|
||||
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
if not stat.S_ISDIR(path.lstat().st_mode):
|
||||
raise ValueError("Transfer directory is not a directory")
|
||||
return path
|
||||
|
||||
|
||||
def locked_file(path: Path, operation: int) -> int:
|
||||
import fcntl
|
||||
|
||||
fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
value = os.fstat(fd)
|
||||
if not stat.S_ISREG(value.st_mode) or value.st_nlink != 1 or value.st_uid != os.getuid():
|
||||
raise ValueError("Unsafe transfer lock")
|
||||
fcntl.flock(fd, operation)
|
||||
return fd
|
||||
except BaseException:
|
||||
os.close(fd)
|
||||
raise
|
||||
|
||||
|
||||
class TransferReservation:
|
||||
def __init__(self, owner: TransferSpace, fd: int, device: int, remaining: int) -> None:
|
||||
self.owner, self.fd, self.device, self.remaining = owner, fd, device, remaining
|
||||
|
||||
def _write(self) -> None:
|
||||
payload = json.dumps(
|
||||
{"version": 1, "device": self.device, "remaining": self.remaining}
|
||||
).encode()
|
||||
os.lseek(self.fd, 0, os.SEEK_SET)
|
||||
os.write(self.fd, payload)
|
||||
os.ftruncate(self.fd, len(payload))
|
||||
|
||||
def written(self, byte_length: int) -> None:
|
||||
"""Release promised space only after these bytes have reached the file."""
|
||||
if byte_length < 0 or byte_length > self.remaining:
|
||||
raise ValueError("Transfer exceeded its reserved length")
|
||||
with self.owner.lock():
|
||||
self.remaining -= byte_length
|
||||
self._write()
|
||||
|
||||
|
||||
class TransferSpace:
|
||||
def __init__(self, root: Path, *, reserve_bytes: int = FREE_RESERVE) -> None:
|
||||
self.root = secure_directory(root)
|
||||
if reserve_bytes < 0:
|
||||
raise ValueError("Invalid free-space reserve")
|
||||
self.reserve_bytes = reserve_bytes
|
||||
|
||||
@contextmanager
|
||||
def lock(self) -> Iterator[None]:
|
||||
import fcntl
|
||||
|
||||
fd = locked_file(self.root / ".lock", fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def _required(self, target: Path, requested: int) -> None:
|
||||
import fcntl
|
||||
|
||||
if type(requested) is not int or requested < 0:
|
||||
raise ValueError("Invalid transfer length")
|
||||
target = secure_directory(target)
|
||||
device = target.stat().st_dev
|
||||
promised = 0
|
||||
for index, path in enumerate(self.root.glob("reservation-*.json")):
|
||||
if index >= 10000:
|
||||
raise TransferCapacityError("Слишком много незавершённых передач.")
|
||||
if not re.fullmatch(r"reservation-[0-9a-f]{32}\.json", path.name):
|
||||
raise ValueError("Unknown reservation owner; preserved")
|
||||
fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW)
|
||||
try:
|
||||
st = os.fstat(fd)
|
||||
if (
|
||||
not stat.S_ISREG(st.st_mode)
|
||||
or st.st_nlink != 1
|
||||
or st.st_uid != os.getuid()
|
||||
or st.st_size > 4096
|
||||
):
|
||||
raise ValueError("Unsafe transfer reservation")
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
active = True
|
||||
else:
|
||||
active = False
|
||||
if not active:
|
||||
# Canonical UUID metadata in this private ledger has no live
|
||||
# owner. It may be torn by a crash; never follow paths from it.
|
||||
# Any partial payload remains counted by filesystem free space.
|
||||
path.unlink()
|
||||
continue
|
||||
row = json.loads(os.read(fd, 4096))
|
||||
if (
|
||||
set(row) != {"version", "device", "remaining"}
|
||||
or row["version"] != 1
|
||||
or type(row["remaining"]) is not int
|
||||
or row["remaining"] < 0
|
||||
or type(row["device"]) is not int
|
||||
):
|
||||
raise ValueError("Unknown live reservation schema; preserved")
|
||||
if row["device"] == device:
|
||||
promised += row["remaining"]
|
||||
finally:
|
||||
os.close(fd)
|
||||
available = max(0, shutil.disk_usage(target).free - promised - self.reserve_bytes)
|
||||
if requested > available:
|
||||
raise TransferCapacityError(
|
||||
f"Недостаточно места для передачи: нужно {requested} байт, "
|
||||
f"доступно {available} байт с учётом текущих передач и резерва."
|
||||
)
|
||||
|
||||
def check(self, target: Path, requested: int) -> None:
|
||||
"""Advisory package preflight; each actual write reserves again atomically."""
|
||||
with self.lock():
|
||||
self._required(target, requested)
|
||||
|
||||
@contextmanager
|
||||
def reservation(self, target: Path, requested: int) -> Iterator[TransferReservation]:
|
||||
import fcntl
|
||||
|
||||
path = self.root / f"reservation-{uuid.uuid4().hex}.json"
|
||||
with self.lock():
|
||||
self._required(target, requested)
|
||||
fd = locked_file(path, fcntl.LOCK_EX)
|
||||
reservation = TransferReservation(self, fd, target.stat().st_dev, requested)
|
||||
try:
|
||||
reservation._write()
|
||||
os.fsync(fd)
|
||||
except BaseException:
|
||||
os.close(fd)
|
||||
path.unlink(missing_ok=True)
|
||||
raise
|
||||
try:
|
||||
yield reservation
|
||||
finally:
|
||||
with self.lock():
|
||||
path.unlink(missing_ok=True)
|
||||
os.close(fd)
|
||||
@@ -6,6 +6,7 @@ import struct
|
||||
import subprocess
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
@@ -70,18 +71,20 @@ class RecordedCameraFrameService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: SessionStore,
|
||||
store: SessionStore | None,
|
||||
inspector: RecordedMediaInspector,
|
||||
*,
|
||||
ffmpeg_path: Path,
|
||||
cache_root: Path,
|
||||
max_decode_lanes: int = _DEFAULT_MAX_DECODE_LANES,
|
||||
max_source_manifests: int = _DEFAULT_MAX_SOURCE_MANIFESTS,
|
||||
manifest_provider: Callable[[str, str], RecordedMediaManifest] | None = None,
|
||||
) -> None:
|
||||
resolved_ffmpeg = ffmpeg_path.expanduser().resolve(strict=True)
|
||||
if not resolved_ffmpeg.is_file() or not os.access(resolved_ffmpeg, os.X_OK):
|
||||
raise SessionIntegrityError("ffmpeg is unavailable for camera frame review")
|
||||
self._store = store
|
||||
self._manifest_provider = manifest_provider
|
||||
self._inspector = inspector
|
||||
self._ffmpeg_path = resolved_ffmpeg
|
||||
self._cache_root = cache_root.expanduser().absolute()
|
||||
@@ -217,16 +220,21 @@ class RecordedCameraFrameService:
|
||||
self._source_manifests.move_to_end(source_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
replay = self._store.prepare_replay(session_id, speed=1.0, loop=False)
|
||||
matches = tuple(
|
||||
artifact
|
||||
for artifact in self._store.list_recorded_media(session_id)
|
||||
if artifact.source_path.name == expected_source_name
|
||||
)
|
||||
if len(matches) != 1:
|
||||
raise SessionIntegrityError("recorded camera source is unavailable")
|
||||
artifact = matches[0]
|
||||
manifest = self._inspector.inspect(artifact, replay)
|
||||
if self._manifest_provider is not None:
|
||||
manifest = self._manifest_provider(session_id, expected_source_name)
|
||||
else:
|
||||
if self._store is None:
|
||||
raise SessionIntegrityError("Recorded camera source provider is unavailable")
|
||||
replay = self._store.prepare_replay(session_id, speed=1.0, loop=False)
|
||||
matches = tuple(
|
||||
artifact
|
||||
for artifact in self._store.list_recorded_media(session_id)
|
||||
if artifact.source_path.name == expected_source_name
|
||||
)
|
||||
if len(matches) != 1:
|
||||
raise SessionIntegrityError("recorded camera source is unavailable")
|
||||
artifact = matches[0]
|
||||
manifest = self._inspector.inspect(artifact, replay)
|
||||
with self._coordination:
|
||||
bound = self._source_manifests.get(source_key)
|
||||
if bound is None:
|
||||
|
||||
@@ -502,6 +502,8 @@ class SessionStore:
|
||||
raise ValueError("LAB id must use the form 'LAB E21'")
|
||||
_validate_identifier(result_kind, "LAB result kind")
|
||||
_validate_identifier(result_id, "LAB result id")
|
||||
if (self.data_dir / "lab-deletions" / "blocked" / (result_id + ".json")).exists():
|
||||
raise SessionIntegrityError("LAB was explicitly deleted; republication is blocked")
|
||||
if source_result_id is not None:
|
||||
_validate_identifier(source_result_id, "LAB source result id")
|
||||
if config_sha256 is not None and SHA256_PATTERN.fullmatch(config_sha256) is None:
|
||||
@@ -763,6 +765,12 @@ class SessionStore:
|
||||
connection.commit()
|
||||
return normalized_name
|
||||
|
||||
def validate_lab_projection(self, session_id: str) -> None:
|
||||
"""Validate catalog ownership before any physical storage mutation."""
|
||||
_validate_identifier(session_id, "LAB session id")
|
||||
with self._lock, self._connect() as connection:
|
||||
_require_capability_owned_lab_projection(connection, session_id)
|
||||
|
||||
def delete_capability_lab_projection(self, session_id: str) -> None:
|
||||
"""Delete only one typed LAB catalog projection and its copied rows.
|
||||
|
||||
@@ -1868,10 +1876,10 @@ def _require_capability_owned_lab_projection(
|
||||
if (
|
||||
summary["archive_id"] != LAB_ARCHIVE_ID
|
||||
or summary["origin"] != LAB_ORIGIN
|
||||
or binding.replay_capability is None
|
||||
or binding.session_id != session_id
|
||||
or binding.source_session_id == session_id
|
||||
or lab["include_recorded_media"] not in {0, 1}
|
||||
or (lab["include_recorded_media"] not in {0, 1}
|
||||
and binding.replay_capability is not None)
|
||||
or connection.execute(
|
||||
"SELECT 1 FROM observation_lab_instances WHERE session_id = ?",
|
||||
(binding.source_session_id,),
|
||||
@@ -1882,6 +1890,16 @@ def _require_capability_owned_lab_projection(
|
||||
"observation session is not a capability-owned LAB projection"
|
||||
)
|
||||
_operator_display_name_from_row(lab["operator_display_name"])
|
||||
if binding.replay_capability is None:
|
||||
# Old publications predate the media-copy flag. Catalog mutations do not
|
||||
# grant replay and never traverse or remove evidence paths.
|
||||
source = connection.execute(
|
||||
"SELECT origin FROM observation_sessions WHERE session_id = ?",
|
||||
(binding.source_session_id,),
|
||||
).fetchone()
|
||||
if source is None or source["origin"] == LAB_ORIGIN:
|
||||
raise SessionIntegrityError("LAB projection source ownership is invalid")
|
||||
return summary, lab
|
||||
_validate_existing_lab_projection(
|
||||
connection,
|
||||
session_id=session_id,
|
||||
@@ -1891,7 +1909,8 @@ def _require_capability_owned_lab_projection(
|
||||
duration_seconds=summary["duration_seconds"],
|
||||
include_recorded_media=bool(lab["include_recorded_media"]),
|
||||
require_recorded_replay=(
|
||||
binding.replay_capability.viewer_profile == "recorded-session"
|
||||
binding.replay_capability is not None
|
||||
and binding.replay_capability.viewer_profile == "recorded-session"
|
||||
),
|
||||
)
|
||||
return summary, lab
|
||||
|
||||
+72
-922
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
"""Operator policy and explicit management of reproducible presentation copies."""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Path
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from k1link.laboratory.local_presentations import LocalPresentationError, LocalPresentations
|
||||
|
||||
|
||||
class RetentionPolicy(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
retention_days: int = Field(ge=1, le=365)
|
||||
|
||||
|
||||
class PinCopy(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
pinned: bool
|
||||
|
||||
|
||||
CopyId = Annotated[str, Path(min_length=1, max_length=200, pattern=r"^[a-zA-Z0-9._:-]+$")]
|
||||
|
||||
|
||||
def build_local_storage_router(store: LocalPresentations) -> APIRouter:
|
||||
router = APIRouter(prefix="/api/v1/storage/laboratory", tags=["storage"])
|
||||
|
||||
def invoke(action):
|
||||
try:
|
||||
return action()
|
||||
except (LocalPresentationError, OSError, ValueError) as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
|
||||
@router.get("")
|
||||
def snapshot():
|
||||
return invoke(store.snapshot)
|
||||
|
||||
@router.put("/policy")
|
||||
def policy(value: RetentionPolicy):
|
||||
return invoke(lambda: store.policy(value.retention_days))
|
||||
|
||||
@router.put("/copies/{result_id}/pin")
|
||||
def pin(result_id: CopyId, value: PinCopy):
|
||||
return invoke(lambda: store.pin(result_id, value.pinned))
|
||||
|
||||
@router.delete("/copies/{result_id}")
|
||||
def remove(result_id: CopyId):
|
||||
return invoke(lambda: store.remove(result_id))
|
||||
|
||||
return router
|
||||
@@ -7,6 +7,7 @@ from typing import Any
|
||||
from fastapi import APIRouter, HTTPException, Query, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from k1link.laboratory.data_deletion import LabDeletionError
|
||||
from k1link.observatory.composition_runs import (
|
||||
CompositionRun,
|
||||
CompositionRunError,
|
||||
@@ -31,8 +32,10 @@ from k1link.observatory.portable_queue_binding import (
|
||||
from k1link.observatory.portable_run_definitions import PortableRunDefinitionRegistry
|
||||
from k1link.observatory.recorded_jobs import (
|
||||
ObservatoryRecordedJobQueue,
|
||||
ObservatoryRecordedQueueConflictError,
|
||||
ObservatoryRecordedQueueDuplicateError,
|
||||
ObservatoryRecordedQueueError,
|
||||
ObservatoryRecordedQueueNotFoundError,
|
||||
)
|
||||
from k1link.observatory.source_admission import PortableSourceNotPreparedError
|
||||
from k1link.sessions import SessionNotFoundError, SessionStore
|
||||
@@ -118,6 +121,7 @@ def build_modular_observatory_router(
|
||||
binding: PortableRecordedQueueBindingService | None = None,
|
||||
queue: ObservatoryRecordedJobQueue | None = None,
|
||||
view_profiles: LabViewProfileStore | None = None,
|
||||
deletion_service=None,
|
||||
) -> APIRouter:
|
||||
router = APIRouter()
|
||||
|
||||
@@ -391,6 +395,8 @@ def build_modular_observatory_router(
|
||||
except (
|
||||
CompositionRunError,
|
||||
ObservatoryRecordedQueueError,
|
||||
ObservatoryRecordedQueueNotFoundError,
|
||||
ObservatoryRecordedQueueConflictError,
|
||||
ObservatoryOntologyError,
|
||||
ValueError,
|
||||
) as exc:
|
||||
@@ -427,9 +433,31 @@ def build_modular_observatory_router(
|
||||
if composition_runs is None:
|
||||
raise HTTPException(503, "Композиции AI-слоя недоступны.")
|
||||
try:
|
||||
composition_runs.delete_projection(run_id)
|
||||
except CompositionRunError as exc:
|
||||
raise HTTPException(404, "Результат AI Inference не найден.") from exc
|
||||
if deletion_service is None:
|
||||
raise HTTPException(503, "Полное удаление LAB пока недоступно.")
|
||||
deletion_service.delete("composition", run_id)
|
||||
except (LabDeletionError, CompositionRunError) as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
return Response(status_code=204)
|
||||
|
||||
@router.delete("/api/v1/observatory/ai-runs/{job_id}", status_code=204)
|
||||
def delete_failed_run_projection(job_id: str) -> Response:
|
||||
if queue is None:
|
||||
raise HTTPException(503, "Очередь AI-слоёв недоступна.")
|
||||
try:
|
||||
if deletion_service is None:
|
||||
raise HTTPException(503, "Полное удаление LAB пока недоступно.")
|
||||
deletion_service.delete("job", job_id)
|
||||
except LabDeletionError as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
except ObservatoryRecordedQueueNotFoundError as exc:
|
||||
raise HTTPException(404, "Запуск не найден.") from exc
|
||||
except ObservatoryRecordedQueueConflictError as exc:
|
||||
raise HTTPException(
|
||||
409, "Удалить можно только завершённую ошибочную попытку без результата."
|
||||
) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, "Некорректный идентификатор запуска.") from exc
|
||||
return Response(status_code=204)
|
||||
|
||||
@router.get("/api/v1/observatory/ai-runs")
|
||||
@@ -449,7 +477,8 @@ def build_modular_observatory_router(
|
||||
for job in queue.list_jobs(
|
||||
source_session_id=source_session_id,
|
||||
setup_id=setup_id,
|
||||
limit=20,
|
||||
limit=500,
|
||||
include_hidden=False,
|
||||
)
|
||||
]
|
||||
except (ObservatoryRecordedQueueError, ValueError) as exc:
|
||||
@@ -457,7 +486,7 @@ def build_modular_observatory_router(
|
||||
jobs.sort(key=lambda job: job.created_at_utc, reverse=True)
|
||||
return {
|
||||
"schema_version": "missioncore.observatory-recorded-job-list/v1",
|
||||
"items": [job.as_dict() for job in jobs[:20]],
|
||||
"items": [job.as_dict() for job in jobs],
|
||||
"authority": {
|
||||
"commands_enabled": False,
|
||||
"actuation_allowed": False,
|
||||
|
||||
@@ -7,6 +7,7 @@ from fastapi import Path as ApiPath
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from k1link.laboratory.data_deletion import LabDeletionError
|
||||
from k1link.observatory import (
|
||||
LaboratorySetupRegistry,
|
||||
ObservatoryRunPreparationCapacityError,
|
||||
@@ -173,6 +174,7 @@ def build_observatory_router(
|
||||
portable_setup_projector: PortableSetupProjector | PortableLabV1SetupProjector | None = None,
|
||||
portable_setup_projector_error: str | None = None,
|
||||
portable_binding_service: PortableRecordedQueueBindingService | None = None,
|
||||
deletion_service=None,
|
||||
portable_result_view: PortableResultViewService | None = None,
|
||||
portable_artifact_transport: PortableObservatoryArtifactTransport | None = None,
|
||||
portable_result_publisher: PortableObservatoryResultPublisher | None = None,
|
||||
@@ -1139,6 +1141,7 @@ def build_observatory_router(
|
||||
setup_id=setup_id,
|
||||
definition_sha256=definition_sha256,
|
||||
limit=limit,
|
||||
include_hidden=False,
|
||||
)
|
||||
except (ObservatoryRecordedQueueError, ValueError) as exc:
|
||||
raise HTTPException(
|
||||
@@ -1329,7 +1332,12 @@ def build_observatory_router(
|
||||
)
|
||||
def delete_observatory_lab_projection(session_id: str) -> Response:
|
||||
try:
|
||||
store.delete_capability_lab_projection(session_id)
|
||||
if deletion_service is None:
|
||||
store.validate_lab_projection(session_id)
|
||||
raise HTTPException(503, "Полное удаление LAB пока недоступно.")
|
||||
deletion_service.delete("lab", session_id)
|
||||
except LabDeletionError as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
except SessionNotFoundError as exc:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
|
||||
@@ -52,6 +52,8 @@ from k1link.observatory.recorded_jobs import (
|
||||
RecordedExecutorIdentity,
|
||||
)
|
||||
from k1link.observatory.recorded_progress import RecordedProgress
|
||||
from k1link.observatory.transfer_space import TransferCapacityError
|
||||
from k1link.web.source_transfer_response import SourceTransferFileResponse
|
||||
|
||||
OBSERVATORY_WORKER_CAPABILITY_CLAIM_REQUEST_SCHEMA: Final = (
|
||||
"missioncore.observatory-worker-claim-request/v2"
|
||||
@@ -67,9 +69,7 @@ OBSERVATORY_WORKER_SUCCEED_REQUEST_SCHEMA: Final = (
|
||||
OBSERVATORY_WORKER_FAIL_REQUEST_SCHEMA: Final = "missioncore.observatory-worker-fail-request/v1"
|
||||
OBSERVATORY_WORKER_CONTOUR_HEADER: Final = "X-Mission-Core-Contour-Id"
|
||||
OBSERVATORY_WORKER_CLAIM_TOKEN_HEADER: Final = "X-Mission-Core-Claim-Token"
|
||||
OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER: Final = (
|
||||
"X-Mission-Core-Claim-Generation"
|
||||
)
|
||||
OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER: Final = "X-Mission-Core-Claim-Generation"
|
||||
|
||||
_IDENTIFIER = re.compile(r"^[a-z][a-z0-9-]{2,95}$")
|
||||
_SHA256 = re.compile(r"^[a-f0-9]{64}$")
|
||||
@@ -175,8 +175,7 @@ class ObservatoryWorkerClaimRequest(_StrictWorkerRequest):
|
||||
@model_validator(mode="after")
|
||||
def validate_capability_snapshot(self) -> ObservatoryWorkerClaimRequest:
|
||||
identities = tuple(
|
||||
capability.recorded_identity()
|
||||
for capability in self.supported_executor_identities
|
||||
capability.recorded_identity() for capability in self.supported_executor_identities
|
||||
)
|
||||
if len(identities) != len(set(identities)):
|
||||
raise ValueError("executor capabilities must be unique")
|
||||
@@ -306,11 +305,14 @@ def build_observatory_worker_router(
|
||||
)
|
||||
)
|
||||
if claim is None:
|
||||
return Response(status_code=204, headers={
|
||||
"X-Mission-Core-Idle-Claim": (
|
||||
"non-binding" if request.schema_version.endswith("/v3") else "durable"
|
||||
),
|
||||
})
|
||||
return Response(
|
||||
status_code=204,
|
||||
headers={
|
||||
"X-Mission-Core-Idle-Claim": (
|
||||
"non-binding" if request.schema_version.endswith("/v3") else "durable"
|
||||
),
|
||||
},
|
||||
)
|
||||
return claim.as_dict()
|
||||
|
||||
@router.get("/recorded-jobs/{job_id}")
|
||||
@@ -345,10 +347,14 @@ def build_observatory_worker_router(
|
||||
request: ObservatoryWorkerProgressRequest,
|
||||
job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)],
|
||||
) -> Response:
|
||||
_queue_call(lambda: queue.report_progress(
|
||||
job_id, claim_token=request.claim_token,
|
||||
claimant_id=authentication.contour_id, progress=request.progress,
|
||||
))
|
||||
_queue_call(
|
||||
lambda: queue.report_progress(
|
||||
job_id,
|
||||
claim_token=request.claim_token,
|
||||
claimant_id=authentication.contour_id,
|
||||
progress=request.progress,
|
||||
)
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
@router.post("/recorded-jobs/{job_id}/checkpoint")
|
||||
@@ -434,9 +440,7 @@ def build_observatory_worker_router(
|
||||
status_code=409,
|
||||
detail="Recorded result is not awaiting publication.",
|
||||
)
|
||||
package_root = _artifact_call(
|
||||
lambda: artifact_transport.package_root_for_terminal(job)
|
||||
)
|
||||
package_root = _artifact_call(lambda: artifact_transport.package_root_for_terminal(job))
|
||||
try:
|
||||
result_publisher.publish(job=job, package_root=package_root)
|
||||
except PortableResultPublisherError as exc:
|
||||
@@ -487,8 +491,7 @@ def build_observatory_worker_router(
|
||||
claim_token=claim_token,
|
||||
claim_generation=claim_generation,
|
||||
claimant_id=authentication.contour_id,
|
||||
)
|
||||
.as_dict()
|
||||
).as_dict()
|
||||
)
|
||||
|
||||
@router.get("/recorded-jobs/{job_id}/source-camera-epoch-archive")
|
||||
@@ -506,25 +509,32 @@ def build_observatory_worker_router(
|
||||
Header(alias=OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER, ge=1),
|
||||
],
|
||||
) -> FileResponse:
|
||||
archive, path = _artifact_call(
|
||||
lambda: artifact_transport.materialize_camera_epoch_archive(
|
||||
job_id=job_id,
|
||||
claim_token=claim_token,
|
||||
claim_generation=claim_generation,
|
||||
claimant_id=authentication.contour_id,
|
||||
lease_fd = artifact_transport.source_lifecycle.acquire_reader()
|
||||
try:
|
||||
archive, path = _artifact_call(
|
||||
lambda: artifact_transport.materialize_camera_epoch_archive(
|
||||
job_id=job_id,
|
||||
claim_token=claim_token,
|
||||
claim_generation=claim_generation,
|
||||
claimant_id=authentication.contour_id,
|
||||
)
|
||||
)
|
||||
)
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=PORTABLE_CAMERA_EPOCH_ARCHIVE_MEDIA_TYPE,
|
||||
headers={
|
||||
"ETag": f'"{archive.sha256}"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Mission-Core-Content-Sha256": archive.sha256,
|
||||
PORTABLE_CAMERA_EPOCH_ARCHIVE_ID_HEADER: archive.archive_id,
|
||||
},
|
||||
)
|
||||
response = SourceTransferFileResponse(
|
||||
path,
|
||||
media_type=PORTABLE_CAMERA_EPOCH_ARCHIVE_MEDIA_TYPE,
|
||||
headers={
|
||||
"ETag": f'"{archive.sha256}"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Mission-Core-Content-Sha256": archive.sha256,
|
||||
PORTABLE_CAMERA_EPOCH_ARCHIVE_ID_HEADER: archive.archive_id,
|
||||
},
|
||||
)
|
||||
response.lease_fd = lease_fd
|
||||
return response
|
||||
except BaseException:
|
||||
os.close(lease_fd)
|
||||
raise
|
||||
|
||||
@router.get("/recorded-jobs/{job_id}/source-members/{member_id}")
|
||||
def source_member(
|
||||
@@ -542,29 +552,34 @@ def build_observatory_worker_router(
|
||||
Header(alias=OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER, ge=1),
|
||||
],
|
||||
) -> FileResponse:
|
||||
member, path = _artifact_call(
|
||||
lambda: artifact_transport.materialize_source_member(
|
||||
job_id=job_id,
|
||||
member_id=member_id,
|
||||
claim_token=claim_token,
|
||||
claim_generation=claim_generation,
|
||||
claimant_id=authentication.contour_id,
|
||||
lease_fd = artifact_transport.source_lifecycle.acquire_reader()
|
||||
try:
|
||||
member, path = _artifact_call(
|
||||
lambda: artifact_transport.materialize_source_member(
|
||||
job_id=job_id,
|
||||
member_id=member_id,
|
||||
claim_token=claim_token,
|
||||
claim_generation=claim_generation,
|
||||
claimant_id=authentication.contour_id,
|
||||
)
|
||||
)
|
||||
)
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=member.media_type,
|
||||
headers={
|
||||
"ETag": f'"{member.sha256}"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Mission-Core-Content-Sha256": member.sha256,
|
||||
},
|
||||
)
|
||||
response = SourceTransferFileResponse(
|
||||
path,
|
||||
media_type=member.media_type,
|
||||
headers={
|
||||
"ETag": f'"{member.sha256}"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Mission-Core-Content-Sha256": member.sha256,
|
||||
},
|
||||
)
|
||||
response.lease_fd = lease_fd
|
||||
return response
|
||||
except BaseException:
|
||||
os.close(lease_fd)
|
||||
raise
|
||||
|
||||
@router.put(
|
||||
"/recorded-jobs/{job_id}/result-packages/{result_sha256}/manifest"
|
||||
)
|
||||
@router.put("/recorded-jobs/{job_id}/result-packages/{result_sha256}/manifest")
|
||||
async def stage_result_manifest(
|
||||
request: Request,
|
||||
job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)],
|
||||
@@ -590,13 +605,10 @@ def build_observatory_worker_router(
|
||||
claim_token=claim_token,
|
||||
claim_generation=claim_generation,
|
||||
claimant_id=authentication.contour_id,
|
||||
)
|
||||
.as_dict()
|
||||
).as_dict()
|
||||
)
|
||||
|
||||
@router.put(
|
||||
"/recorded-jobs/{job_id}/result-packages/{result_sha256}/members/{member_id}"
|
||||
)
|
||||
@router.put("/recorded-jobs/{job_id}/result-packages/{result_sha256}/members/{member_id}")
|
||||
async def upload_result_member(
|
||||
request: Request,
|
||||
job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)],
|
||||
@@ -628,9 +640,7 @@ def build_observatory_worker_router(
|
||||
_raise_artifact_or_queue_error(exc)
|
||||
return plan.as_dict()
|
||||
|
||||
@router.post(
|
||||
"/recorded-jobs/{job_id}/result-packages/{result_sha256}/complete"
|
||||
)
|
||||
@router.post("/recorded-jobs/{job_id}/result-packages/{result_sha256}/complete")
|
||||
def complete_result_package(
|
||||
job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)],
|
||||
result_sha256: Annotated[str, ApiPath(pattern=r"^[a-f0-9]{64}$")],
|
||||
@@ -653,8 +663,7 @@ def build_observatory_worker_router(
|
||||
claim_token=claim_token,
|
||||
claim_generation=claim_generation,
|
||||
claimant_id=authentication.contour_id,
|
||||
)
|
||||
.as_dict()
|
||||
).as_dict()
|
||||
)
|
||||
|
||||
return router
|
||||
@@ -717,6 +726,10 @@ def _queue_call[T](operation: Callable[[], T]) -> T:
|
||||
def _artifact_call[T](operation: Callable[[], T]) -> T:
|
||||
try:
|
||||
return _queue_call(operation)
|
||||
except TransferCapacityError as exc:
|
||||
raise HTTPException(
|
||||
status_code=503, detail=str(exc), headers={"Retry-After": "30"}
|
||||
) from exc
|
||||
except PortableArtifactTransportIntegrityError as exc:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
@@ -735,6 +748,10 @@ def _artifact_call[T](operation: Callable[[], T]) -> T:
|
||||
|
||||
|
||||
def _raise_artifact_or_queue_error(exc: Exception) -> None:
|
||||
if isinstance(exc, TransferCapacityError):
|
||||
raise HTTPException(
|
||||
status_code=503, detail=str(exc), headers={"Retry-After": "30"}
|
||||
) from exc
|
||||
if isinstance(exc, PortableArtifactTransportIntegrityError):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
|
||||
@@ -9,6 +9,7 @@ from fastapi import APIRouter, HTTPException, Path, Query, Response
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from k1link.laboratory.canonical_rerun_overlay import CanonicalLabOverlayError
|
||||
from k1link.laboratory.local_presentations import LOCK as PRESENTATION_LOCK
|
||||
from k1link.observatory.composition_runs import CompositionRunError, CompositionRunStore
|
||||
from k1link.observatory.portable_replay import PortableReplayService
|
||||
from k1link.observatory.portable_result_view import PortableResultViewError
|
||||
@@ -39,6 +40,42 @@ def build_portable_replay_router(
|
||||
router = APIRouter(tags=["observatory"])
|
||||
path = "/api/v1/observatory/portable-results/{result_id}/replays/{base_sha}/recording.rrd"
|
||||
|
||||
class LeasedReplayResponse(FileResponse):
|
||||
def __init__(self, artifact, result_id):
|
||||
self.copy_id = result_id
|
||||
self.copies = getattr(service, "local_copies", None)
|
||||
super().__init__(
|
||||
artifact.path,
|
||||
media_type="application/vnd.rerun.rrd",
|
||||
headers={
|
||||
"ETag": f'"{artifact.sha256}"',
|
||||
"X-Rerun-Format": "RRF2",
|
||||
"Cache-Control": "private, max-age=31536000, immutable",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
)
|
||||
if self.copies is not None:
|
||||
self.copies.acquire(result_id)
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
try:
|
||||
await super().__call__(scope, receive, send)
|
||||
finally:
|
||||
if self.copies is not None:
|
||||
self.copies.release(self.copy_id)
|
||||
|
||||
def read_copy(copy_id, generation, getter):
|
||||
with PRESENTATION_LOCK:
|
||||
try:
|
||||
artifact = getter()
|
||||
except (ValueError, OSError, KeyError, TypeError, PortableResultViewError) as exc:
|
||||
raise HTTPException(409, "Кэш результата не прошёл проверку.") from exc
|
||||
if artifact is None:
|
||||
raise HTTPException(409, "Сохранённый просмотр ещё не подготовлен.")
|
||||
if artifact.sha256 != generation:
|
||||
raise HTTPException(412, "Версия сохранённого просмотра изменилась.")
|
||||
return LeasedReplayResponse(artifact, copy_id)
|
||||
|
||||
@router.head(path)
|
||||
def prepare(result_id: ResultId, base_sha: BaseSha) -> Response:
|
||||
try:
|
||||
@@ -71,24 +108,7 @@ def build_portable_replay_router(
|
||||
base_sha: BaseSha,
|
||||
generation: Annotated[str, Query(pattern=r"^[a-f0-9]{64}$")],
|
||||
) -> FileResponse:
|
||||
try:
|
||||
artifact = service.cached(result_id, base_sha)
|
||||
except (ValueError, OSError, KeyError, TypeError, PortableResultViewError) as exc:
|
||||
raise HTTPException(409, "Кэш результата не прошёл проверку.") from exc
|
||||
if artifact is None:
|
||||
raise HTTPException(409, "Сохранённый просмотр ещё не подготовлен.")
|
||||
if artifact.sha256 != generation:
|
||||
raise HTTPException(412, "Версия сохранённого просмотра изменилась.")
|
||||
return FileResponse(
|
||||
artifact.path,
|
||||
media_type="application/vnd.rerun.rrd",
|
||||
headers={
|
||||
"ETag": f'"{artifact.sha256}"',
|
||||
"X-Rerun-Format": "RRF2",
|
||||
"Cache-Control": "private, max-age=31536000, immutable",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
)
|
||||
return read_copy(result_id, generation, lambda: service.cached(result_id, base_sha))
|
||||
|
||||
composition_path = (
|
||||
"/api/v1/observatory/ai-composition-runs/{run_id}/replays/{base_sha}/recording.rrd"
|
||||
@@ -146,29 +166,10 @@ def build_portable_replay_router(
|
||||
base_sha: BaseSha,
|
||||
generation: Annotated[str, Query(pattern=r"^[a-f0-9]{64}$")],
|
||||
) -> FileResponse:
|
||||
try:
|
||||
artifact = service.cached_composition(run_id, composition_members(run_id), base_sha)
|
||||
except (
|
||||
ValueError,
|
||||
OSError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
PortableResultViewError,
|
||||
) as exc:
|
||||
raise HTTPException(409, "Кэш составного результата не прошёл проверку.") from exc
|
||||
if artifact is None:
|
||||
raise HTTPException(409, "Составной просмотр ещё не подготовлен.")
|
||||
if artifact.sha256 != generation:
|
||||
raise HTTPException(412, "Версия составного просмотра изменилась.")
|
||||
return FileResponse(
|
||||
artifact.path,
|
||||
media_type="application/vnd.rerun.rrd",
|
||||
headers={
|
||||
"ETag": f'"{artifact.sha256}"',
|
||||
"X-Rerun-Format": "RRF2",
|
||||
"Cache-Control": "private, max-age=31536000, immutable",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
return read_copy(
|
||||
run_id,
|
||||
generation,
|
||||
lambda: service.cached_composition(run_id, composition_members(run_id), base_sha),
|
||||
)
|
||||
|
||||
return router
|
||||
|
||||
@@ -21,6 +21,7 @@ from k1link.compute import (
|
||||
RecordedPerceptionOverlayError,
|
||||
RecordedPerceptionVideo,
|
||||
)
|
||||
from k1link.laboratory.worker_gateway import LaboratoryWorkerGateway
|
||||
from k1link.sessions import (
|
||||
LayoutConflictError,
|
||||
MaterializedRecording,
|
||||
@@ -398,6 +399,7 @@ def build_session_router(
|
||||
media_inspector: RecordedMediaInspector | None = None,
|
||||
perception_overlay_provider: RecordedPerceptionOverlayProvider | None = None,
|
||||
perception_media_provider: RecordedPerceptionMediaProvider | None = None,
|
||||
laboratory_gateway: LaboratoryWorkerGateway | None = None,
|
||||
point_color_renderers: Mapping[str, RecordedPointColorRenderer] | None = None,
|
||||
point_display_renderers: Mapping[str, RecordedPointDisplayRenderer] | None = None,
|
||||
lab_calculation_profile_resolver: (
|
||||
@@ -411,6 +413,38 @@ def build_session_router(
|
||||
router = APIRouter(tags=["observation-sessions"])
|
||||
recorded_media_inspector = media_inspector or RecordedMediaInspector()
|
||||
|
||||
def perception_route(path: str, *, methods=None):
|
||||
"""Bind Core to Worker while retaining the existing presentation contracts."""
|
||||
def decorate(handler):
|
||||
if laboratory_gateway is None:
|
||||
return router.api_route(path, methods=methods or ["GET"])(handler)
|
||||
|
||||
async def forward(request: Request, session_id: str):
|
||||
try:
|
||||
command = await run_in_threadpool(
|
||||
_prepare_replay, store, catalog_refresher,
|
||||
session_id, 1.0, False, False,
|
||||
)
|
||||
if request.method == "POST" and command.map_version is not None:
|
||||
raise HTTPException(
|
||||
409, "Слой распознавания относится к исходной геометрии записи.")
|
||||
except SessionNotFoundError as exc:
|
||||
raise HTTPException(404, str(exc)) from exc
|
||||
except (SessionNotReplayableError, SessionIntegrityError) as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, "Некорректный идентификатор сессии.") from exc
|
||||
suffix = path.split("/{session_id}/", 1)[1]
|
||||
for key, value in request.path_params.items():
|
||||
suffix = suffix.replace("{" + key + "}", str(value))
|
||||
return await laboratory_gateway.forward(
|
||||
request, "presentation/sessions/" + session_id + "/" + suffix)
|
||||
|
||||
forward.__name__ = handler.__name__ + "_worker"
|
||||
router.add_api_route(path, forward, methods=methods or ["GET"])
|
||||
return handler
|
||||
return decorate
|
||||
|
||||
@router.get("/api/v1/observation-sessions/{session_id}/display-profile")
|
||||
def get_session_display_profile(session_id: str):
|
||||
from k1link.sessions.display_profile import load_display_profile
|
||||
@@ -540,7 +574,9 @@ def build_session_router(
|
||||
)
|
||||
async def delete_observation_session(session_id: str) -> Response:
|
||||
try:
|
||||
store.get_session(session_id)
|
||||
detail = store.get_session(session_id)
|
||||
if detail.summary.lab is not None:
|
||||
raise HTTPException(409, "Удалите LAB через её историю запусков.")
|
||||
recorded_artifacts = store.list_recorded_media(session_id)
|
||||
except SessionNotFoundError:
|
||||
# DELETE is idempotent. Multiple mounted catalogs or another
|
||||
@@ -1205,7 +1241,7 @@ def build_session_router(
|
||||
},
|
||||
)
|
||||
|
||||
@router.post("/api/v1/observation-sessions/{session_id}/perception.rrd")
|
||||
@perception_route("/api/v1/observation-sessions/{session_id}/perception.rrd", methods=["POST"])
|
||||
async def get_observation_session_perception(
|
||||
session_id: str,
|
||||
request: RecordedPerceptionRequest,
|
||||
@@ -1284,7 +1320,7 @@ def build_session_router(
|
||||
},
|
||||
)
|
||||
|
||||
@router.get("/api/v1/observation-sessions/{session_id}/perception/status")
|
||||
@perception_route("/api/v1/observation-sessions/{session_id}/perception/status")
|
||||
async def get_observation_session_perception_status(
|
||||
session_id: str,
|
||||
response: Response,
|
||||
@@ -1458,7 +1494,7 @@ def build_session_router(
|
||||
return StreamingResponse(chunks(), media_type="application/vnd.nodedc.point-display-stream",
|
||||
headers={"Cache-Control": "no-store, no-transform"})
|
||||
|
||||
@router.get("/api/v1/observation-sessions/{session_id}/perception-media/{result_id}/manifest")
|
||||
@perception_route("/api/v1/observation-sessions/{session_id}/perception-media/{result_id}/manifest")
|
||||
def get_recorded_perception_media_manifest(
|
||||
session_id: str,
|
||||
result_id: str,
|
||||
@@ -1482,7 +1518,7 @@ def build_session_router(
|
||||
},
|
||||
)
|
||||
|
||||
@router.api_route(
|
||||
@perception_route(
|
||||
"/api/v1/observation-sessions/{session_id}/perception-media/{result_id}/recording.mp4",
|
||||
methods=["GET", "HEAD"],
|
||||
)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Keep source-copy readers alive through streaming, ranges and disconnects."""
|
||||
|
||||
import os
|
||||
|
||||
from starlette.responses import FileResponse
|
||||
from starlette.types import Receive, Scope, Send
|
||||
|
||||
|
||||
class SourceTransferFileResponse(FileResponse):
|
||||
lease_fd: int
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
# The response owns the read. Do not delegate pathsend to a server which
|
||||
# could open the pathname after this coroutine has released its lease.
|
||||
extensions = dict(scope.get("extensions", {}))
|
||||
extensions.pop("http.response.pathsend", None)
|
||||
scope = {**scope, "extensions": extensions}
|
||||
try:
|
||||
await super().__call__(scope, receive, send)
|
||||
finally:
|
||||
os.close(self.lease_fd)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Full recorded perception playback prepared exclusively in the Worker volume."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse, Response
|
||||
|
||||
from k1link.compute import (
|
||||
IntegratedPerceptionOverlayStore,
|
||||
RecordedCalibratedFusionStore,
|
||||
RecordedPerceptionEpochStore,
|
||||
RecordedPerceptionOverlayMux,
|
||||
RecordedPerceptionOverlayStore,
|
||||
)
|
||||
from k1link.compute.results import RecordedPerceptionOverlayArtifact
|
||||
from k1link.web.session_api import (
|
||||
RecordedPerceptionPreparationStatus,
|
||||
RecordedPerceptionRequest,
|
||||
_recorded_perception_manifest_document,
|
||||
_recorded_perception_video_response,
|
||||
_require_matching_digest,
|
||||
)
|
||||
|
||||
|
||||
def build_worker_laboratory_presentation(root: Path, ffmpeg: Path) -> APIRouter:
|
||||
router = APIRouter(prefix="/api/v1/laboratory/presentation/sessions")
|
||||
jobs = root / ".runtime/compute-jobs"
|
||||
results = root / ".runtime/compute-results"
|
||||
cache = root / "presentation"
|
||||
legacy = RecordedPerceptionOverlayStore(
|
||||
jobs_root=jobs,
|
||||
results_root=results,
|
||||
cache_root=cache / "perception-overlays",
|
||||
ffmpeg_path=ffmpeg,
|
||||
ffprobe_path=ffmpeg.with_name("ffprobe"),
|
||||
)
|
||||
fusion = RecordedCalibratedFusionStore(
|
||||
jobs_root=jobs,
|
||||
perception_results_root=results,
|
||||
fusion_results_root=root / ".runtime/compute-fusions",
|
||||
cache_root=cache / "calibrated-fusion-overlays",
|
||||
)
|
||||
integrated = IntegratedPerceptionOverlayStore(
|
||||
jobs_root=jobs,
|
||||
results_root=root / ".runtime/compute-experiments/e10/worker-results",
|
||||
lidar_packs_root=root / ".runtime/compute-experiments/e10/lidar-packs",
|
||||
cache_root=cache / "integrated-perception-overlays",
|
||||
ffmpeg_path=ffmpeg,
|
||||
)
|
||||
overlay = RecordedPerceptionOverlayMux(integrated, RecordedPerceptionOverlayMux(fusion, legacy))
|
||||
media = RecordedPerceptionEpochStore(
|
||||
jobs_root=jobs,
|
||||
results_root=results,
|
||||
ffprobe_path=ffmpeg.with_name("ffprobe"),
|
||||
)
|
||||
|
||||
@router.post("/{session_id}/perception.rrd")
|
||||
def recording(session_id: str, request: RecordedPerceptionRequest):
|
||||
artifact = overlay.materialize(session_id, **request.model_dump())
|
||||
if artifact is None:
|
||||
return Response(status_code=204, headers={"Cache-Control": "no-store"})
|
||||
if isinstance(artifact, RecordedPerceptionOverlayArtifact):
|
||||
return FileResponse(
|
||||
artifact.path,
|
||||
media_type="application/vnd.rerun.rrd",
|
||||
filename="perception.rrd",
|
||||
content_disposition_type="inline",
|
||||
headers={
|
||||
"ETag": f'"sha256:{artifact.sha256}"',
|
||||
"Cache-Control": "private, no-cache, no-transform",
|
||||
},
|
||||
)
|
||||
return Response(
|
||||
artifact,
|
||||
media_type="application/vnd.rerun.rrd",
|
||||
headers={"Cache-Control": "private, no-cache, no-transform"},
|
||||
)
|
||||
|
||||
@router.get("/{session_id}/perception/status")
|
||||
def status(
|
||||
session_id: str,
|
||||
recording_id: Annotated[
|
||||
str, Query(min_length=1, max_length=128, pattern=r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
|
||||
],
|
||||
):
|
||||
request = RecordedPerceptionRequest(
|
||||
application_id="nodedc_mission_core_recorded", recording_id=recording_id
|
||||
)
|
||||
return RecordedPerceptionPreparationStatus.model_validate(
|
||||
overlay.status(session_id, recording_id=request.recording_id)
|
||||
)
|
||||
|
||||
def video(session: str, result: str):
|
||||
value = media.video(session, result)
|
||||
if value is None:
|
||||
raise HTTPException(404, "Готовое видео сегментации отсутствует.")
|
||||
return value
|
||||
|
||||
@router.get("/{session_id}/perception-media/{result_id}/manifest")
|
||||
def manifest(session_id: str, result_id: str, if_match: str | None = Header(None)):
|
||||
value = video(session_id, result_id)
|
||||
etag = f'"sha256:{value.sha256}"'
|
||||
_require_matching_digest(etag, if_match)
|
||||
return JSONResponse(
|
||||
_recorded_perception_manifest_document(value),
|
||||
headers={"ETag": etag, "Cache-Control": "private, no-cache"},
|
||||
)
|
||||
|
||||
@router.api_route(
|
||||
"/{session_id}/perception-media/{result_id}/recording.mp4", methods=["GET", "HEAD"]
|
||||
)
|
||||
def movie(
|
||||
request: Request,
|
||||
session_id: str,
|
||||
result_id: str,
|
||||
generation: str,
|
||||
range_header: str | None = Header(None, alias="Range"),
|
||||
):
|
||||
value = video(session_id, result_id)
|
||||
if generation != value.sha256:
|
||||
raise HTTPException(412, "Поколение видео сегментации было заменено.")
|
||||
return _recorded_perception_video_response(
|
||||
value, range_header, head_only=request.method == "HEAD"
|
||||
)
|
||||
|
||||
return router
|
||||
@@ -0,0 +1,890 @@
|
||||
"""Worker-owned legacy LAB presentation and evaluation surface.
|
||||
|
||||
Existing evidence validators and projections are reused unchanged. Only the
|
||||
Worker composes this filesystem-backed surface; the operator uses its transport.
|
||||
The legacy runtime layout is a compatibility binding inside a managed volume,
|
||||
not an operator checkout or a reason to copy compute inputs to the operator.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from k1link.laboratory import (
|
||||
LaboratoryEvidenceRegistry,
|
||||
LaboratoryEvidenceReportService,
|
||||
LaboratoryRunner,
|
||||
LaboratoryValueReviewRegistry,
|
||||
)
|
||||
from k1link.laboratory.m48_raw_evidence import (
|
||||
M48_EXPECTED_THREAT_RESULT_ID,
|
||||
M48RawEvidenceError,
|
||||
M48RawEvidenceReader,
|
||||
)
|
||||
from k1link.sessions import RecordedCameraFrame
|
||||
from k1link.web.advanced_laboratory_api import build_advanced_laboratory_router
|
||||
from k1link.web.e30_engineering_api import build_e30_engineering_router
|
||||
from k1link.web.e30_human_review_api import build_e30_human_review_router
|
||||
from k1link.web.e30_review_api import build_e30_review_router
|
||||
from k1link.web.e40_case_review_api import build_e40_case_review_router
|
||||
from k1link.web.e46_blind_review_api import build_e46_blind_review_router
|
||||
from k1link.web.e46a_ai_engineering_preannotation_api import (
|
||||
build_e46a_ai_engineering_preannotation_router,
|
||||
)
|
||||
from k1link.web.e46b_temporal_motion_api import build_e46b_temporal_motion_router
|
||||
from k1link.web.e46c_full_replay_world_tracks_api import build_e46c_full_replay_world_tracks_router
|
||||
from k1link.web.e46d_temporal_failure_audit_api import build_e46d_temporal_failure_audit_router
|
||||
from k1link.web.e46e_ready_stack_api import build_e46e_ready_stack_router
|
||||
from k1link.web.e46f_dashcam_bakeoff_api import build_e46f_dashcam_bakeoff_router
|
||||
from k1link.web.e46g_rectified_detector_bakeoff_api import (
|
||||
build_e46g_rectified_detector_bakeoff_router,
|
||||
)
|
||||
from k1link.web.e46h_full_rectified_front_replay_api import (
|
||||
build_e46h_full_rectified_front_replay_router,
|
||||
)
|
||||
from k1link.web.e46i_grounding_dino_full_replay_api import (
|
||||
build_e46i_grounding_dino_full_replay_router,
|
||||
)
|
||||
from k1link.web.e46j_raw_fisheye_realtime_api import build_e46j_raw_fisheye_realtime_router
|
||||
from k1link.web.e47_semantic_slam_api import build_e47_semantic_slam_router
|
||||
from k1link.web.l3_pointpillars_visual_api import build_l3_pointpillars_visual_router
|
||||
from k1link.web.l31_pointpillars_ravnoves_api import build_l31_pointpillars_ravnoves_router
|
||||
from k1link.web.l32_pointpillars_camera_review_api import (
|
||||
build_l32_pointpillars_camera_review_router,
|
||||
)
|
||||
from k1link.web.l33_camera_first_detector_review_api import (
|
||||
build_l33_camera_first_detector_review_router,
|
||||
)
|
||||
from k1link.web.l34_annotation_api import (
|
||||
build_l34_annotation_router,
|
||||
build_l34d_blind_annotation_router,
|
||||
)
|
||||
from k1link.web.l34_right_yolox_truth_island_api import (
|
||||
build_l34_right_yolox_truth_island_freeze_router,
|
||||
)
|
||||
from k1link.web.l34a_assisted_yolox_error_audit_api import (
|
||||
build_l34a_assisted_yolox_error_audit_router,
|
||||
)
|
||||
from k1link.web.l34b_nested_box_consolidation_api import build_l34b_nested_box_consolidation_router
|
||||
from k1link.web.l34c_tile_seam_stitch_api import build_l34c_tile_seam_stitch_router
|
||||
from k1link.web.l34d_cumulative_postprocessing_api import (
|
||||
build_l34d_cumulative_postprocessing_router,
|
||||
)
|
||||
from k1link.web.l34e_self_review_diagnostic_api import build_l34e_self_review_diagnostic_router
|
||||
from k1link.web.l34f_adjudication_api import build_l34f_adjudication_router
|
||||
from k1link.web.laboratory_api import build_laboratory_router
|
||||
from k1link.web.laboratory_report_api import build_laboratory_report_router
|
||||
from k1link.web.m4_threat_replay_api import build_m4_threat_replay_router
|
||||
from k1link.web.m48_object_quality_api import build_m48_object_quality_router
|
||||
from k1link.web.m48r3_static_occupancy_api import build_m48r3_static_occupancy_router
|
||||
from k1link.web.m48s_fixed_class_detector_lab_api import build_m48s_fixed_class_detector_lab_router
|
||||
from k1link.web.m48t_risk_quality_lab_api import build_m48t_risk_quality_lab_router
|
||||
from k1link.web.m49_physical_safety_playback_api import build_m49_physical_safety_playback_router
|
||||
from k1link.web.m49_tgs_fail_closed_api import build_m49_tgs_fail_closed_router
|
||||
from k1link.web.m49_tgs_full_shadow_api import build_m49_tgs_full_shadow_router
|
||||
from k1link.web.vegetation_shadow_lab_api import (
|
||||
build_vegetation_benchmark_lab_router,
|
||||
build_vegetation_shadow_lab_router,
|
||||
)
|
||||
|
||||
|
||||
def build_worker_laboratory_router(
|
||||
*,
|
||||
repository_root: Path,
|
||||
configuration_root: Path,
|
||||
presentation_root: Path,
|
||||
camera_frame_provider: Callable[[str, int], RecordedCameraFrame] | None = None,
|
||||
camera_playback_provider: Callable | None = None,
|
||||
canonical_recording_provider: Callable[[str], tuple[Path, str] | None] | None = None,
|
||||
ffmpeg_path: Path | None = None,
|
||||
evaluation_runner: LaboratoryRunner | None = None,
|
||||
) -> APIRouter:
|
||||
"""Compose identical LAB routes against Worker-owned evidence and result roots."""
|
||||
router = APIRouter()
|
||||
evidence_registry = LaboratoryEvidenceRegistry.from_directory(
|
||||
configuration_root / "laboratories"
|
||||
)
|
||||
value_registry = LaboratoryValueReviewRegistry.from_file(
|
||||
configuration_root / "laboratory-value-review.json"
|
||||
)
|
||||
reports = LaboratoryEvidenceReportService(
|
||||
evidence_registry, lambda: repository_root / ".runtime" / "compute-experiments"
|
||||
)
|
||||
try:
|
||||
raw_evidence = M48RawEvidenceReader.from_repository(
|
||||
repository_root=repository_root,
|
||||
threat_result_root=repository_root
|
||||
/ ".runtime/compute-experiments/m4/replay-threat"
|
||||
/ M48_EXPECTED_THREAT_RESULT_ID,
|
||||
)
|
||||
except (M48RawEvidenceError, OSError, ValueError):
|
||||
raw_evidence = None
|
||||
|
||||
router.include_router(
|
||||
build_laboratory_router(
|
||||
e29_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e29" / "results"
|
||||
),
|
||||
local_surface_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "k1-local-surface-v1"
|
||||
/ "models"
|
||||
),
|
||||
source_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e10" / "lidar-packs"
|
||||
),
|
||||
source_result_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e10" / "worker-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_laboratory_report_router(
|
||||
value_registry,
|
||||
reports,
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_advanced_laboratory_router(
|
||||
evidence_registry=evidence_registry,
|
||||
evidence_runtime_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments"
|
||||
),
|
||||
e31_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e31"
|
||||
/ "source-qualifications"
|
||||
),
|
||||
e32_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e32" / "results"
|
||||
),
|
||||
e33_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e33" / "results"
|
||||
),
|
||||
e34_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e34" / "results"
|
||||
),
|
||||
e35_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e35" / "results"
|
||||
),
|
||||
e37_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e37" / "results"
|
||||
),
|
||||
e38_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e38" / "results"
|
||||
),
|
||||
e39_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e39" / "results"
|
||||
),
|
||||
e40_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e40" / "results"
|
||||
),
|
||||
l3_visual_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "l3" / "visual-audits"
|
||||
),
|
||||
l31_ravnoves_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "pointpillars-ravnoves"
|
||||
),
|
||||
l32_camera_review_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "pointpillars-camera-review"
|
||||
),
|
||||
l33_camera_first_review_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "camera-first-detector-review"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l3_pointpillars_visual_router(
|
||||
root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "l3" / "visual-audits"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l31_pointpillars_ravnoves_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "pointpillars-ravnoves"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l32_pointpillars_camera_review_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "pointpillars-camera-review"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l33_camera_first_detector_review_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "camera-first-detector-review"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34_right_yolox_truth_island_freeze_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46_blind_review_router(
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
annotation_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "laboratory-annotations" / "e46-blind"
|
||||
),
|
||||
submission_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e48" / "review-submissions"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46a_ai_engineering_preannotation_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e46a"
|
||||
/ "ai-engineering-preannotations"
|
||||
),
|
||||
annotation_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "laboratory-annotations" / "e46a-correction"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46b_temporal_motion_router(
|
||||
root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46b" / "temporal-motion"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46c_full_replay_world_tracks_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e46c"
|
||||
/ "full-replay-world-tracks"
|
||||
),
|
||||
e26_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e10" / "worker-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46d_temporal_failure_audit_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e46d"
|
||||
/ "temporal-failure-audits"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m4_threat_replay_router(
|
||||
root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "m4" / "replay-threat"
|
||||
),
|
||||
repository_root_provider=lambda: repository_root,
|
||||
camera_frame_provider=(
|
||||
camera_frame_provider if camera_frame_provider is not None else None
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m48_object_quality_router(
|
||||
pack_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48"
|
||||
/ "object-quality-packs"
|
||||
),
|
||||
workflow_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "laboratory-annotations" / "m48-object-quality"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "m48" / "object-truth-seals"
|
||||
),
|
||||
result_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48"
|
||||
/ "object-quality-results"
|
||||
),
|
||||
small_static_result_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48"
|
||||
/ "small-static-passage-regression-results"
|
||||
),
|
||||
static_occupancy_result_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48"
|
||||
/ "static-occupancy-qualification-results"
|
||||
),
|
||||
camera_frame_provider=(
|
||||
camera_frame_provider if camera_frame_provider is not None else None
|
||||
),
|
||||
camera_playback_provider=(camera_playback_provider),
|
||||
spatial_evidence_provider=raw_evidence,
|
||||
evaluation_runner=evaluation_runner,
|
||||
evaluation_receipt_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "laboratory-run-receipts"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m48r3_static_occupancy_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48"
|
||||
/ "static-occupancy-shadow-results"
|
||||
),
|
||||
repository_root_provider=lambda: repository_root,
|
||||
camera_frame_provider=(
|
||||
camera_frame_provider if camera_frame_provider is not None else None
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m49_tgs_fail_closed_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m49"
|
||||
/ "tgs-fail-closed-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m49_tgs_full_shadow_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m49"
|
||||
/ "tgs-full-shadow-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_vegetation_shadow_lab_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "lab-v1-vegetation"
|
||||
/ "results"
|
||||
),
|
||||
canonical_recording_provider=canonical_recording_provider,
|
||||
camera_frame_provider=(
|
||||
camera_frame_provider if camera_frame_provider is not None else None
|
||||
),
|
||||
jobs_root=repository_root / ".runtime" / "compute-jobs",
|
||||
rerun_overlay_cache_root=(presentation_root / "laboratory-rerun-overlays"),
|
||||
ffmpeg_path=ffmpeg_path,
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_vegetation_benchmark_lab_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "lab-v1-vegetation-benchmark"
|
||||
/ "results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m49_physical_safety_playback_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m49"
|
||||
/ "physical-safety-playback-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m48s_fixed_class_detector_lab_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48s-semantic-shadow"
|
||||
/ "fixed-class-detector-lab-results"
|
||||
),
|
||||
repository_root_provider=lambda: repository_root,
|
||||
camera_frame_provider=(
|
||||
camera_frame_provider if camera_frame_provider is not None else None
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_m48t_risk_quality_lab_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48t-risk-quality"
|
||||
/ "lab-results"
|
||||
),
|
||||
native_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "m48t-risk-quality"
|
||||
/ "native-lab-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e47_semantic_slam_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e47"
|
||||
/ "semantic-slam-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46e_ready_stack_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e46e"
|
||||
/ "ready-stack-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46f_dashcam_bakeoff_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e46f"
|
||||
/ "dashcam-bakeoff-results"
|
||||
),
|
||||
e46e_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e46e"
|
||||
/ "ready-stack-results"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46g_rectified_detector_bakeoff_router(
|
||||
root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46g" / "results"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46h_full_rectified_front_replay_router(
|
||||
root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46h" / "results"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46i_grounding_dino_full_replay_router(
|
||||
root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46i" / "results"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e46j_raw_fisheye_realtime_router(
|
||||
root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46j" / "results"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34_annotation_router(
|
||||
root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
annotation_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "laboratory-annotations" / "l34"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34a_assisted_yolox_error_audit_router(
|
||||
audit_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "assisted-yolox-error-audits"
|
||||
),
|
||||
l34_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34b_nested_box_consolidation_router(
|
||||
shadow_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "nested-box-consolidation-shadows"
|
||||
),
|
||||
l34_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34c_tile_seam_stitch_router(
|
||||
shadow_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "tile-seam-stitch-shadows"
|
||||
),
|
||||
l34_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34d_cumulative_postprocessing_router(
|
||||
candidate_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "cumulative-postprocessing-candidates"
|
||||
),
|
||||
l34_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34d_blind_annotation_router(
|
||||
candidate_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "cumulative-postprocessing-candidates"
|
||||
),
|
||||
l34_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
annotation_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "laboratory-annotations" / "l34d-blind"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34e_self_review_diagnostic_router(
|
||||
diagnostic_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "self-review-diagnostics"
|
||||
),
|
||||
candidate_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "cumulative-postprocessing-candidates"
|
||||
),
|
||||
l34_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_l34f_adjudication_router(
|
||||
diagnostic_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "self-review-diagnostics"
|
||||
),
|
||||
candidate_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "cumulative-postprocessing-candidates"
|
||||
),
|
||||
l34_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "right-yolox-truth-island-freeze"
|
||||
),
|
||||
truth_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e46" / "results"
|
||||
),
|
||||
evaluation_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs"
|
||||
),
|
||||
adjudication_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "laboratory-annotations" / "l34f-adjudication"
|
||||
),
|
||||
result_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "l3"
|
||||
/ "adjudicated-references"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e30_review_router(
|
||||
materialization_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e30" / "materializations"
|
||||
),
|
||||
review_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e30" / "review-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e40_case_review_router(
|
||||
e40_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e40" / "results"
|
||||
),
|
||||
operator_review_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e40" / "operator-reviews"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e30_engineering_router(
|
||||
generation_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e30"
|
||||
/ "engineering-generations"
|
||||
),
|
||||
materialization_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e30" / "materializations"
|
||||
),
|
||||
review_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e30" / "review-packs"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
router.include_router(
|
||||
build_e30_human_review_router(
|
||||
materialization_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e30" / "materializations"
|
||||
),
|
||||
review_pack_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e30" / "review-packs"
|
||||
),
|
||||
engineering_generation_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e30"
|
||||
/ "engineering-generations"
|
||||
),
|
||||
draft_root_provider=lambda: (
|
||||
repository_root / ".runtime" / "compute-experiments" / "e30" / "human-review-drafts"
|
||||
),
|
||||
generation_root_provider=lambda: (
|
||||
repository_root
|
||||
/ ".runtime"
|
||||
/ "compute-experiments"
|
||||
/ "e30"
|
||||
/ "human-review-generations"
|
||||
),
|
||||
)
|
||||
)
|
||||
return router
|
||||
Reference in New Issue
Block a user