Restore complete LAB recordings from verified Worker publications

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 03:23:20 +03:00
parent a724a9796a
commit 1317f78672
11 changed files with 635 additions and 12 deletions
@@ -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)
+9 -1
View File
@@ -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")
+7 -4
View File
@@ -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):
+150
View File
@@ -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()
+150
View File
@@ -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)
+6
View File
@@ -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