From 1317f78672afc5735f485fb52a3c595f7e3174ac Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Tue, 10 Nov 2026 03:23:20 +0300 Subject: [PATCH] Restore complete LAB recordings from verified Worker publications --- src/k1link/laboratory/deletion_coordinator.py | 2 +- src/k1link/laboratory/deletion_inventory.py | 10 +- src/k1link/laboratory/local_presentations.py | 11 +- src/k1link/laboratory/replay_publication.py | 150 ++++++++++++ src/k1link/laboratory/replay_restore.py | 150 ++++++++++++ src/k1link/laboratory/worker_server.py | 6 + src/k1link/observatory/portable_replay.py | 26 ++- src/k1link/web/app.py | 11 +- src/k1link/web/portable_replay_api.py | 3 + src/k1link/web/worker_ready_replays.py | 65 ++++++ tests/test_ready_lab_replays.py | 213 ++++++++++++++++++ 11 files changed, 635 insertions(+), 12 deletions(-) create mode 100644 src/k1link/laboratory/replay_publication.py create mode 100644 src/k1link/laboratory/replay_restore.py create mode 100644 src/k1link/web/worker_ready_replays.py create mode 100644 tests/test_ready_lab_replays.py diff --git a/src/k1link/laboratory/deletion_coordinator.py b/src/k1link/laboratory/deletion_coordinator.py index 5f1e4eb1..83586e14 100644 --- a/src/k1link/laboratory/deletion_coordinator.py +++ b/src/k1link/laboratory/deletion_coordinator.py @@ -34,7 +34,7 @@ class LabDeletionCoordinator: 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, + return {"owners": [identity] + [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) diff --git a/src/k1link/laboratory/deletion_inventory.py b/src/k1link/laboratory/deletion_inventory.py index 85033d5c..d175dbe8 100644 --- a/src/k1link/laboratory/deletion_inventory.py +++ b/src/k1link/laboratory/deletion_inventory.py @@ -129,7 +129,8 @@ def inventory_local(store: OwnedLabData, selected: list[str]): def inventory_worker(store: OwnedLabData, selected: list[str]): selected = set(selected) - table = {key: set() for key in selected if _JOB.fullmatch(key)} + table = {key: set() for key in selected if _JOB.fullmatch(key) + or re.fullmatch(r"ai-composition-[a-f0-9]{64}", key)} lab = store.roots.get("lab") if lab is None: raise LabDeletionError("LAB storage mounts are not configured") @@ -170,6 +171,13 @@ def inventory_worker(store: OwnedLabData, selected: list[str]): for cache in (lab / "presentation").glob("*"): if cache.is_dir(): _replays(table, selected, "lab", lab, cache) + from k1link.laboratory.replay_publication import ReplayManifest + for key in selected: + for manifest in (lab / "presentation/portable-replays" / key).glob("*/manifest.json"): + doc = ReplayManifest.model_validate(_read(manifest)) + if doc.result_id != key or manifest.parent.name != doc.base_sha256: + raise LabDeletionError("Ready replay ownership mismatch") + _add(table, key, "lab", lab, _files(manifest.parent)) archive_root = store.roots.get("archive") if archive_root is None: raise LabDeletionError("LAB archive mount is unavailable") diff --git a/src/k1link/laboratory/local_presentations.py b/src/k1link/laboratory/local_presentations.py index eb208656..41dfd2c1 100644 --- a/src/k1link/laboratory/local_presentations.py +++ b/src/k1link/laboratory/local_presentations.py @@ -24,9 +24,12 @@ class LocalPresentationError(ValueError): 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" + def __init__(self, data_dir: Path, *, clock: Callable[[], float] = time.time, + cache_data_dir: Path | None = None): + self.data_dir = data_dir + cache_data_dir = cache_data_dir or data_dir + self.root = cache_data_dir / "observatory-portable-replay-cache" + self.index = cache_data_dir / "lab-local-storage.json" self.clock = clock self.leases: dict[str, int] = {} @@ -147,7 +150,7 @@ class LocalPresentations: return self.snapshot() def _require_not_deleted(self, result_id: str): - if (self.index.parent / "lab-deletions" / "blocked" / (result_id + ".json")).exists(): + if (self.data_dir / "lab-deletions" / "blocked" / (result_id + ".json")).exists(): raise LocalPresentationError("LAB удаляется или уже удалена.") def acquire(self, result_id: str): diff --git a/src/k1link/laboratory/replay_publication.py b/src/k1link/laboratory/replay_publication.py new file mode 100644 index 00000000..f9d4028c --- /dev/null +++ b/src/k1link/laboratory/replay_publication.py @@ -0,0 +1,150 @@ +"""Immutable, Worker-owned complete LAB viewing products (not inference inputs).""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import tempfile +from collections import Counter +from pathlib import Path + +from pydantic import BaseModel, ConfigDict, Field + +from k1link.laboratory.data_deletion import LOCK, LabDeletionError, _write + +REPLAY_ID = ( + r"^(?:ai-composition|m49-tgs-portable-review|lab-v1-eomt-ddrnet|" + r"ai-layer-(?:ddrnet|eomt|rf-detr|object-distance))-[a-f0-9]{64}$" +) +SHA = r"^[a-f0-9]{64}$" +MAX_REPLAY_BYTES = 1024**3 + + +class ReplayManifest(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + schema_version: str = Field(pattern=r"^missioncore.ready-lab-replay/v1$") + result_id: str = Field(pattern=REPLAY_ID) + base_sha256: str = Field(pattern=SHA) + cache_key: str = Field(pattern=SHA) + sha256: str = Field(pattern=SHA) + byte_length: int = Field(ge=4, le=MAX_REPLAY_BYTES) + + +def checked_file(path: Path, digest: str, size: int) -> None: + if path.resolve() != path.absolute() or not path.is_file() or path.stat().st_size != size: + raise ValueError("Invalid ready replay file") + before = path.stat() + with path.open("rb") as stream: + if stream.read(4) != b"RRF2": + raise ValueError("Invalid ready replay format") + stream.seek(0) + if hashlib.file_digest(stream, "sha256").hexdigest() != digest: + raise ValueError("Ready replay checksum mismatch") + after = path.stat() + if (before.st_ino, before.st_size, before.st_mtime_ns) != ( + after.st_ino, + after.st_size, + after.st_mtime_ns, + ): + raise ValueError("Ready replay changed during verification") + + +class ReplayPublications: + def __init__(self, runtime_root: Path): + self.runtime = runtime_root.absolute() + self.root = self.runtime / "presentation" / "portable-replays" + self.active: Counter[str] = Counter() + self._verified: dict[Path, tuple] = {} + + def directory(self, result_id: str, base_sha: str) -> Path: + if re.fullmatch(REPLAY_ID, result_id) is None or re.fullmatch(SHA, base_sha) is None: + raise ValueError("Invalid ready replay identity") + path = self.root / result_id / base_sha + if path.resolve() != path.absolute(): + raise ValueError("Linked ready replay directory") + return path + + def require_alive(self, result_id: str): + if (self.runtime / "state/data-ownership/receipts" / (result_id + ".json")).exists(): + raise LabDeletionError("Deleted replay cannot be read or republished") + + def read(self, result_id: str, base_sha: str) -> tuple[ReplayManifest, Path]: + self.require_alive(result_id) + folder = self.directory(result_id, base_sha) + path = folder / "manifest.json" + if path.is_symlink() or path.stat().st_size > 8192: + raise ValueError("Invalid replay manifest") + manifest = ReplayManifest.model_validate_json(path.read_bytes()) + if manifest.result_id != result_id or manifest.base_sha256 != base_sha: + raise ValueError("Replay manifest binding mismatch") + payload = folder / (manifest.sha256 + ".rrd") + if payload.is_symlink(): + raise ValueError("Linked replay payload") + if not payload.is_file(): + raise ValueError("Published replay payload is missing") + stat = payload.stat() + stamp = (manifest.sha256, stat.st_ino, stat.st_size, stat.st_mtime_ns) + if self._verified.get(payload) != stamp: + checked_file(payload, manifest.sha256, manifest.byte_length) + if len(self._verified) >= 128: + self._verified.clear() + self._verified[payload] = stamp + return manifest, payload + + def publish(self, manifest: ReplayManifest, source: Path): + """Internal producer/migration API. Existing generations never get overwritten.""" + with LOCK: + self.require_alive(manifest.result_id) + folder = self.directory(manifest.result_id, manifest.base_sha256) + if (folder / "manifest.json").exists(): + current, _ = self.read(manifest.result_id, manifest.base_sha256) + if current != manifest: + raise ValueError("Ready replay generation is immutable") + return current + checked_file(source, manifest.sha256, manifest.byte_length) + folder.mkdir(parents=True, exist_ok=True) + if shutil.disk_usage(folder).free < manifest.byte_length + 40 * 1024**3: + raise ValueError("Worker free-space reserve reached") + target = folder / (manifest.sha256 + ".rrd") + if target.exists(): + checked_file(target, manifest.sha256, manifest.byte_length) + else: + fd, name = tempfile.mkstemp(prefix=".publish-", dir=folder) + temporary = Path(name) + try: + with os.fdopen(fd, "wb") as output, source.open("rb") as incoming: + shutil.copyfileobj(incoming, output, 1024**2) + output.flush() + os.fsync(output.fileno()) + checked_file(temporary, manifest.sha256, manifest.byte_length) + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + _write(folder / "manifest.json", manifest.model_dump()) + return manifest + + +def main(): + import argparse + + parser = argparse.ArgumentParser(description="Publish an accepted full LAB recording on Worker") + parser.add_argument("--runtime-root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--source", type=Path, required=True) + args = parser.parse_args() + from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority + + authority = WorkerLaboratoryAuthority.from_environment() + if authority is None or authority.runtime_root != args.runtime_root.resolve(): + raise RuntimeError("Publication requires the configured Worker runtime") + result = ReplayPublications(args.runtime_root).publish( + ReplayManifest.model_validate_json(args.manifest.read_bytes()), args.source + ) + print(json.dumps(result.model_dump(), sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/src/k1link/laboratory/replay_restore.py b/src/k1link/laboratory/replay_restore.py new file mode 100644 index 00000000..2d38e841 --- /dev/null +++ b/src/k1link/laboratory/replay_restore.py @@ -0,0 +1,150 @@ +"""Fetch a complete ready LAB product; never download model inputs to rebuild it.""" + +from __future__ import annotations + +import logging +import os +import tempfile +import time +from pathlib import Path + +import httpx + +from k1link.cache_budget import cache_publication +from k1link.laboratory.canonical_rerun_overlay import CanonicalLabReplayArtifact +from k1link.laboratory.data_deletion import _write +from k1link.laboratory.replay_publication import ReplayManifest, checked_file +from k1link.laboratory.worker_gateway import LaboratoryGatewayConfiguration + +_LOG = logging.getLogger(__name__) + + +class WorkerReplayRestore: + def __init__( + self, + configuration: LaboratoryGatewayConfiguration, + *, + transport: httpx.BaseTransport | None = None, + ): + self.configuration = configuration + self.transport = transport + + def restore(self, result_id: str, base_sha: str, key: str, cache: Path): + started = time.monotonic() + prefix = f"/api/v1/laboratory/portable-replays/{result_id}/{base_sha}" + # Endpoint/credentials come only from the existing verified LAB binding. + with httpx.Client( + base_url=self.configuration.base_url, + transport=self.transport, + timeout=httpx.Timeout(60, connect=5), + follow_redirects=False, + trust_env=False, + headers={ + "Authorization": "Bearer " + self.configuration.token(), + "Accept-Encoding": "identity", + }, + ) as client: + with client.stream("GET", prefix) as response: + if response.status_code == 404: + return None # A not-yet-migrated legacy product keeps its existing path. + response.raise_for_status() + body = bytearray() + for chunk in response.iter_bytes(8192): + body.extend(chunk) + if len(body) > 8192: + raise ValueError("Ready replay manifest exceeds limit") + doc = ReplayManifest.model_validate_json(bytes(body)) + if (doc.result_id, doc.base_sha256, doc.cache_key) != (result_id, base_sha, key): + raise ValueError("Worker replay does not match the accepted LAB generation") + target = cache / (doc.sha256 + ".replay.rrd") + sidecar = cache / (key + ".json") + with cache_publication(cache, doc.byte_length + 8192): + fd, name = tempfile.mkstemp(prefix=".restore-", suffix=".part", dir=cache) + partial = Path(name) + os.close(fd) + transferred = 0 + try: + for attempt in range(3): + offset = partial.stat().st_size + headers = ( + {"Range": f"bytes={offset}-", "If-Range": f'"{doc.sha256}"'} + if offset + else {} + ) + try: + with client.stream( + "GET", + prefix + "/recording.rrd", + params={"generation": doc.sha256}, + headers=headers, + ) as response: + if response.status_code not in (200, 206): + response.raise_for_status() + raise ValueError("Unexpected Worker replay response") + if response.headers.get("etag") != f'"{doc.sha256}"': + raise ValueError("Worker replay ETag changed") + if ( + response.headers.get("content-encoding", "identity") + != "identity" + ): + raise ValueError("Encoded replay cannot be resumed") + append = response.status_code == 206 + if append and ( + not offset + or response.headers.get("content-range") + != f"bytes {offset}-{doc.byte_length - 1}/{doc.byte_length}" + ): + raise ValueError("Worker replay resume offset mismatch") + position = offset if append else 0 + if ( + int(response.headers.get("content-length", "-1")) + != doc.byte_length - position + ): + raise ValueError("Worker replay response length mismatch") + with partial.open("ab" if append else "wb") as output: + for chunk in response.iter_raw(1024**2): + if time.monotonic() - started > 30 * 60: + raise ValueError( + "Worker replay transfer deadline exceeded" + ) + if position + len(chunk) > doc.byte_length: + raise ValueError( + "Worker replay exceeds declared length" + ) + output.write(chunk) + position += len(chunk) + transferred += len(chunk) + output.flush() + os.fsync(output.fileno()) + if position != doc.byte_length: + raise httpx.ReadError("Truncated ready replay") + break + except (httpx.TransportError, httpx.TimeoutException): + if attempt == 2: + raise + checked_file(partial, doc.sha256, doc.byte_length) + if target.exists(): + checked_file(target, doc.sha256, doc.byte_length) + else: + os.replace(partial, target) + _write( + sidecar, + { + "key": key, + "file": target.name, + "sha256": doc.sha256, + "byte_length": doc.byte_length, + }, + ) + _LOG.info( + "LAB ready replay restored result=%s bytes=%d transferred=%d " + "seconds=%.3f sha256=%s", + result_id, + doc.byte_length, + transferred, + time.monotonic() - started, + doc.sha256, + ) + return CanonicalLabReplayArtifact(target, doc.byte_length, doc.sha256) + finally: + partial.unlink(missing_ok=True) diff --git a/src/k1link/laboratory/worker_server.py b/src/k1link/laboratory/worker_server.py index 5903d447..8b3680c8 100644 --- a/src/k1link/laboratory/worker_server.py +++ b/src/k1link/laboratory/worker_server.py @@ -23,6 +23,7 @@ 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.replay_publication import ReplayPublications from k1link.laboratory.worker_gateway import LaboratoryGatewayConfiguration from k1link.laboratory.worker_recorded_sources import ( WorkerCanonicalRecordings, @@ -34,6 +35,7 @@ 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 +from k1link.web.worker_ready_replays import build_ready_replay_router def create_app() -> FastAPI: @@ -72,6 +74,7 @@ def create_app() -> FastAPI: manifest_provider=sources.manifest, ) surface_reader = K1LocalSurfaceReadService() + ready_replays = ReplayPublications(root) @asynccontextmanager async def lifespan(app): @@ -107,6 +110,8 @@ def create_app() -> FastAPI: def delete_owned_data(value: DataDeletionRequest): try: with DELETION_LOCK: + if any(ready_replays.active[key] for key in value.owner_ids): + raise LabDeletionError("LAB replay is currently being downloaded") inventory_worker(owned_data, value.owner_ids) return owned_data.delete(value.owner_ids) except (LabDeletionError, OSError, ValueError) as exc: @@ -157,6 +162,7 @@ def create_app() -> FastAPI: local_surface_read_service=surface_reader, ) ) + app.include_router(build_ready_replay_router(ready_replays)) if ffmpeg.is_file(): app.include_router(build_worker_laboratory_presentation(root, ffmpeg)) return app diff --git a/src/k1link/observatory/portable_replay.py b/src/k1link/observatory/portable_replay.py index 0e78483a..59906251 100644 --- a/src/k1link/observatory/portable_replay.py +++ b/src/k1link/observatory/portable_replay.py @@ -1,4 +1,4 @@ -"""Bounded, cached native replay packaging on Core; no inference or Worker IO.""" +"""Ready Worker replay restoration with bounded legacy native packaging.""" from __future__ import annotations @@ -12,6 +12,7 @@ import tempfile import threading from collections import OrderedDict from collections.abc import Callable +from contextlib import nullcontext from pathlib import Path from typing import Any, cast @@ -26,8 +27,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.laboratory.replay_restore import WorkerReplayRestore from k1link.observatory.portable_object_replay import ( RENDERER_VERSION as OBJECT_RENDERER_VERSION, ) @@ -71,13 +72,16 @@ class PortableReplayService: recording_source: Callable[[str], tuple[Path, str] | None], ffmpeg_path: Path, local_copies: LocalPresentations | None = None, + remote_replays: WorkerReplayRestore | None = None, ) -> None: self.view = view self.data_dir = data_dir self.media = media self.recording_source = recording_source self.ffmpeg_path = ffmpeg_path - self.cache = data_dir / "observatory-portable-replay-cache" + self.cache = (local_copies.root if local_copies else + data_dir / "observatory-portable-replay-cache") + self.remote_replays = remote_replays self.local_copies = local_copies self._verified: OrderedDict[tuple[Path, str], tuple[int, ...]] = OrderedDict() @@ -144,11 +148,17 @@ class PortableReplayService: 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 PRESENTATION_LOCK, _LOCK: + with _LOCK, (self.local_copies.use(result_id) if self.local_copies else nullcontext()): cached = self.cached(result_id, base_sha) if cached is not None: return cached key, view = self._key(result_id, base_sha) + if self.remote_replays is not None: + restored = self.remote_replays.restore(result_id, base_sha, key, self.cache) + if restored is not None: + if self.local_copies is not None: + self.local_copies.register(result_id, restored, self.cache / f"{key}.json") + return restored base = self.recording_source(view["source_session_id"]) if base is None or base[1] != base_sha: raise PortableReplayError("source recording generation is not ready") @@ -322,11 +332,17 @@ class PortableReplayService: def prepare_composition( self, run_id: str, result_ids: tuple[str, ...], base_sha: str ) -> CanonicalLabReplayArtifact: - with PRESENTATION_LOCK, _LOCK: + with _LOCK, (self.local_copies.use(run_id) if self.local_copies else nullcontext()): cached = self.cached_composition(run_id, result_ids, base_sha) if cached is not None: return cached key, views = self._composition_key(run_id, result_ids, base_sha) + if self.remote_replays is not None: + restored = self.remote_replays.restore(run_id, base_sha, key, self.cache) + if restored is not None: + if self.local_copies is not None: + self.local_copies.register(run_id, restored, self.cache / f"{key}.json") + return restored source_session_id = cast(str, views[0]["source_session_id"]) base = self.recording_source(source_session_id) if base is None or base[1] != base_sha: diff --git a/src/k1link/web/app.py b/src/k1link/web/app.py index b5117bc2..56a0cbe6 100644 --- a/src/k1link/web/app.py +++ b/src/k1link/web/app.py @@ -18,6 +18,7 @@ from k1link import __version__ from k1link.artifact_gateway import configured_artifact_gateway from k1link.laboratory.deletion_coordinator import LabDeletionCoordinator from k1link.laboratory.local_presentations import LocalPresentations +from k1link.laboratory.replay_restore import WorkerReplayRestore from k1link.laboratory.worker_gateway import ( LaboratoryGatewayConfiguration, LaboratoryWorkerGateway, @@ -997,7 +998,13 @@ async def device_plugin_events(websocket: WebSocket, plugin_id: str) -> None: await websocket.close(code=1011, reason="Device plugin state stream failed") -local_presentation_copies = LocalPresentations(session_store.data_dir) +_replay_cache_binding = os.environ.get("MISSIONCORE_LAB_VIEW_CACHE_DIR", "").strip() +local_presentation_copies = LocalPresentations( + session_store.data_dir, + cache_data_dir=( + Path(_replay_cache_binding).expanduser().absolute() if _replay_cache_binding else None + ), +) lab_deletion_service = LabDeletionCoordinator( store=session_store, queue=OBSERVATORY_RECORDED_JOB_QUEUE, compositions=OBSERVATORY_AI_COMPOSITION_RUNS, copies=local_presentation_copies, @@ -1017,6 +1024,8 @@ if session_artifact_gateway is not None and _ffmpeg is not None: recording_source=_canonical_lab_recording_source, ffmpeg_path=_ffmpeg, local_copies=local_presentation_copies, + remote_replays=WorkerReplayRestore(laboratory_worker_gateway.configuration) + if laboratory_worker_gateway.configuration is not None else None, ), composition_runs=OBSERVATORY_AI_COMPOSITION_RUNS, queue=OBSERVATORY_RECORDED_JOB_QUEUE, diff --git a/src/k1link/web/portable_replay_api.py b/src/k1link/web/portable_replay_api.py index 6e792f03..24a0698f 100644 --- a/src/k1link/web/portable_replay_api.py +++ b/src/k1link/web/portable_replay_api.py @@ -5,6 +5,7 @@ from __future__ import annotations import logging from typing import Annotated +import httpx from fastapi import APIRouter, HTTPException, Path, Query, Response from fastapi.responses import FileResponse @@ -81,6 +82,7 @@ def build_portable_replay_router( try: artifact = service.prepare(result_id, base_sha) except ( + httpx.HTTPError, ValueError, OSError, KeyError, @@ -139,6 +141,7 @@ def build_portable_replay_router( try: artifact = service.prepare_composition(run_id, composition_members(run_id), base_sha) except ( + httpx.HTTPError, ValueError, OSError, KeyError, diff --git a/src/k1link/web/worker_ready_replays.py b/src/k1link/web/worker_ready_replays.py new file mode 100644 index 00000000..fafe2601 --- /dev/null +++ b/src/k1link/web/worker_ready_replays.py @@ -0,0 +1,65 @@ +"""Authenticated Worker API for complete immutable LAB recordings.""" + +from typing import Annotated + +from fastapi import APIRouter, HTTPException, Path, Query +from fastapi.responses import FileResponse + +from k1link.laboratory.data_deletion import LOCK, LabDeletionError +from k1link.laboratory.replay_publication import REPLAY_ID, SHA, ReplayPublications + + +def build_ready_replay_router(store: ReplayPublications) -> APIRouter: + router = APIRouter(prefix="/api/v1/laboratory/portable-replays") + identity = "/{result_id}/{base_sha}" + + def read(result_id, base_sha): + try: + return store.read(result_id, base_sha) + except FileNotFoundError as exc: + raise HTTPException(404, "Ready LAB recording is not published") from exc + except (ValueError, OSError, LabDeletionError) as exc: + raise HTTPException(409, "Ready LAB recording failed verification") from exc + + @router.get(identity) + def manifest( + result_id: Annotated[str, Path(pattern=REPLAY_ID)], + base_sha: Annotated[str, Path(pattern=SHA)], + ): + with LOCK: + doc, _ = read(result_id, base_sha) + return doc.model_dump() + + class LeasedResponse(FileResponse): + async def __call__(self, scope, receive, send): + try: + await super().__call__(scope, receive, send) + finally: + with LOCK: + store.active[self.owner] -= 1 + + @router.get(identity + "/recording.rrd") + def recording( + result_id: Annotated[str, Path(pattern=REPLAY_ID)], + base_sha: Annotated[str, Path(pattern=SHA)], + generation: Annotated[str, Query(pattern=SHA)], + ): + with LOCK: + doc, path = read(result_id, base_sha) + if doc.sha256 != generation: + raise HTTPException(412, "Ready LAB generation changed") + response = LeasedResponse( + path, + media_type="application/vnd.rerun.rrd", + headers={ + "ETag": f'"{doc.sha256}"', + "X-Rerun-Format": "RRF2", + "Cache-Control": "private, max-age=31536000, immutable", + "X-Content-Type-Options": "nosniff", + }, + ) + response.owner = result_id + store.active[result_id] += 1 + return response + + return router diff --git a/tests/test_ready_lab_replays.py b/tests/test_ready_lab_replays.py new file mode 100644 index 00000000..24d4f3d3 --- /dev/null +++ b/tests/test_ready_lab_replays.py @@ -0,0 +1,213 @@ +import hashlib +import json + +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from k1link.laboratory.local_presentations import LocalPresentations +from k1link.laboratory.replay_publication import ReplayManifest, ReplayPublications +from k1link.laboratory.replay_restore import WorkerReplayRestore +from k1link.laboratory.worker_gateway import LaboratoryGatewayConfiguration +from k1link.web.worker_ready_replays import build_ready_replay_router + +ID = "ai-layer-ddrnet-" + "a" * 64 +BASE = "b" * 64 +KEY = "c" * 64 +PAYLOAD = b"RRF2" + bytes(range(256)) * 8192 + + +def manifest(payload=PAYLOAD): + return ReplayManifest( + schema_version="missioncore.ready-lab-replay/v1", + result_id=ID, + base_sha256=BASE, + cache_key=KEY, + sha256=hashlib.sha256(payload).hexdigest(), + byte_length=len(payload), + ) + + +def restore(tmp_path, handler): + token = tmp_path / "token" + token.write_text("a" * 64) + return WorkerReplayRestore( + LaboratoryGatewayConfiguration("http://localhost", token), + transport=httpx.MockTransport(handler), + ) + + +class Interrupted(httpx.SyncByteStream): + def __iter__(self): + yield PAYLOAD[: 1024**2] + raise httpx.ReadError("network interrupted") + + +def response(payload, doc, offset=0): + headers = {"etag": f'"{doc.sha256}"', "content-length": str(len(payload))} + if offset: + headers["content-range"] = f"bytes {offset}-{doc.byte_length - 1}/{doc.byte_length}" + return httpx.Response(206 if offset else 200, headers=headers, stream=httpx.ByteStream(payload)) + + +def test_cold_transfer_resumes_and_seals_verified_copy(tmp_path): + doc = manifest() + calls = [] + + def handler(request): + calls.append(request) + if not request.url.path.endswith(".rrd"): + return httpx.Response(200, json=doc.model_dump()) + if len(calls) == 2: + return httpx.Response( + 200, + headers={"etag": f'"{doc.sha256}"', "content-length": str(doc.byte_length)}, + stream=Interrupted(), + ) + assert request.headers["range"] == f"bytes={1024**2}-" + assert request.headers["if-range"] == f'"{doc.sha256}"' + return response(PAYLOAD[1024**2 :], doc, 1024**2) + + cache = tmp_path / "observatory-portable-replay-cache" + result = restore(tmp_path, handler).restore(ID, BASE, KEY, cache) + assert result.path.read_bytes() == PAYLOAD + assert json.loads((cache / (KEY + ".json")).read_text())["sha256"] == doc.sha256 + assert not list(cache.glob("*.part")) + assert len(calls) == 3 + + +@pytest.mark.parametrize("error", ["hash", "etag", "length", "identity", "redirect", "unavailable"]) +def test_bad_remote_never_publishes_or_falls_back(tmp_path, error): + doc = manifest() + + def handler(request): + if not request.url.path.endswith(".rrd"): + value = doc.model_dump() + if error == "identity": + value["cache_key"] = "d" * 64 + if error == "redirect": + return httpx.Response(302, headers={"location": "https://untrusted.invalid/"}) + if error == "unavailable": + return httpx.Response(503) + return httpx.Response(200, json=value) + content = b"RRF2" + b"x" * (len(PAYLOAD) - 4) if error == "hash" else PAYLOAD + answer = response(content, doc) + if error == "etag": + answer.headers["etag"] = '"wrong"' + if error == "length": + answer.headers["content-length"] = "42" + return answer + + cache = tmp_path / "observatory-portable-replay-cache" + with pytest.raises((ValueError, httpx.HTTPError)): + restore(tmp_path, handler).restore(ID, BASE, KEY, cache) + assert not list(cache.glob("*.rrd")) + assert not list(cache.glob("*.json")) + assert not list(cache.glob("*.part")) + + +def test_legacy_missing_publication_is_explicit(tmp_path): + service = restore(tmp_path, lambda _: httpx.Response(404)) + assert service.restore(ID, BASE, KEY, tmp_path / "observatory-portable-replay-cache") is None + + +def test_worker_publication_immutable_range_and_generation(tmp_path): + source = tmp_path / "source.rrd" + source.write_bytes(PAYLOAD) + store = ReplayPublications(tmp_path) + doc = manifest() + store.publish(doc, source) + app = FastAPI() + app.include_router(build_ready_replay_router(store)) + client = TestClient(app) + prefix = f"/api/v1/laboratory/portable-replays/{ID}/{BASE}" + assert client.get(prefix).json() == doc.model_dump() + assert client.get(prefix + "/recording.rrd?generation=" + "e" * 64).status_code == 412 + answer = client.get( + prefix + "/recording.rrd?generation=" + doc.sha256, + headers={"Range": "bytes=4-15", "If-Range": f'"{doc.sha256}"'}, + ) + assert answer.status_code == 206 and answer.content == PAYLOAD[4:16] + assert store.active[ID] == 0 + with pytest.raises(ValueError, match="immutable"): + store.publish(manifest(b"RRF2different"), source) + store.publish(doc, source) # Exact retry is idempotent. + (tmp_path / "state/data-ownership/receipts").mkdir(parents=True) + (tmp_path / "state/data-ownership/receipts" / (ID + ".json")).write_text("{}") + assert client.get(prefix).status_code == 409 + + +def test_cache_override_keeps_working_copies_and_deletion_block(tmp_path): + original = LocalPresentations(tmp_path) + original.policy(30) + before = original.index.read_bytes() + scratch = LocalPresentations(tmp_path, cache_data_dir=tmp_path / "scratch") + assert scratch.snapshot()["entries"] == {} + scratch.policy(7) + assert original.index.read_bytes() == before + blocked = tmp_path / "lab-deletions/blocked" / (ID + ".json") + blocked.parent.mkdir(parents=True) + blocked.write_text("{}") + with pytest.raises(ValueError): + scratch.acquire(ID) + + +def test_missing_published_payload_is_not_legacy_absence(tmp_path): + source = tmp_path / "source.rrd" + source.write_bytes(PAYLOAD) + store = ReplayPublications(tmp_path) + doc = manifest() + store.publish(doc, source) + app = FastAPI() + app.include_router(build_ready_replay_router(store)) + client = TestClient(app) + (store.directory(ID, BASE) / (doc.sha256 + ".rrd")).unlink() + assert client.get(f"/api/v1/laboratory/portable-replays/{ID}/{BASE}").status_code == 409 + + +def test_published_composition_is_owned_and_deleted_without_source(tmp_path): + from k1link.laboratory.data_deletion import OwnedLabData + from k1link.laboratory.deletion_inventory import inventory_worker + roots = {name: tmp_path / name for name in ("lab", "archive", "ai", "tgs")} + for path in roots.values(): + path.mkdir() + source = tmp_path / "source.rrd" + source.write_bytes(PAYLOAD) + store = ReplayPublications(roots["lab"]) + doc = manifest().model_copy(update={"result_id": "ai-composition-" + "d" * 64}) + store.publish(doc, source) + (roots["archive"] / "catalog.json").write_text( + '{"schema_version":"missioncore.laboratory-archive-catalog/v1","groups":[]}' + ) + owned = OwnedLabData(roots["lab"] / "state/data-ownership", roots) + inventory_worker(owned, [doc.result_id]) + owned.delete([doc.result_id]) + assert not (store.directory(doc.result_id, BASE) / "manifest.json").exists() + assert source.read_bytes() == PAYLOAD + + +def test_composition_deletion_includes_ready_product_but_keeps_shared_jobs(tmp_path): + from types import SimpleNamespace + + from k1link.laboratory.deletion_coordinator import LabDeletionCoordinator + + selected = SimpleNamespace(run_id="ai-composition-" + "d" * 64, job_ids=["shared", "own"]) + retained = SimpleNamespace(run_id="ai-composition-" + "e" * 64, job_ids=["shared"]) + jobs = { + key: SimpleNamespace(job_id=key, state="succeeded", result_id=key + "-result") + for key in ("shared", "own") + } + coordinator = LabDeletionCoordinator( + store=SimpleNamespace(data_dir=tmp_path), + queue=SimpleNamespace(get=jobs.__getitem__), + compositions=SimpleNamespace( + get=lambda _: selected, list=lambda **_: [selected, retained] + ), + copies=None, + gateway=None, + ) + plan = coordinator._plan("composition", selected.run_id) + assert plan["owners"] == [selected.run_id, "own", "own-result"] + assert plan["jobs"] == ["own"] + assert plan["sessions"] == ["own-result"]