refactor(lab): move execution to Worker and manage replay and transfer lifecycles

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:09:39 +03:00
parent cd34b6ce1a
commit fe5900ff3b
101 changed files with 9305 additions and 2256 deletions
+192
View File
@@ -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()
+181
View File
@@ -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})
+197
View File
@@ -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)
+12 -14
View File
@@ -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()
+224
View File
@@ -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)
+167
View File
@@ -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)