Assemble complete modular LAB recordings on Worker before readiness
This commit is contained in:
@@ -178,6 +178,12 @@ def inventory_worker(store: OwnedLabData, selected: list[str]):
|
||||
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))
|
||||
for key in selected:
|
||||
build = lab / "presentation/replay-builds" / key
|
||||
if build.is_dir():
|
||||
if _read(build / "plan.json").get("result_id") != key:
|
||||
raise LabDeletionError("Replay build ownership mismatch")
|
||||
_add(table, key, "lab", lab, _files(build))
|
||||
archive_root = store.roots.get("archive")
|
||||
if archive_root is None:
|
||||
raise LabDeletionError("LAB archive mount is unavailable")
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Durable, authenticated Worker assembly of complete modular LAB recordings.
|
||||
|
||||
Only digest-addressed inputs are accepted. Staging belongs to one composition;
|
||||
publication is immutable and staging is retired after its last consumer (the builder).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from k1link.laboratory.data_deletion import LOCK, _write
|
||||
from k1link.laboratory.replay_publication import (
|
||||
MAX_REPLAY_BYTES,
|
||||
SHA,
|
||||
ReplayManifest,
|
||||
ReplayPublications,
|
||||
checked_file,
|
||||
)
|
||||
from k1link.observatory.portable_replay import PortableReplayService
|
||||
from k1link.observatory.portable_result_view import PortableResultViewService
|
||||
from k1link.observatory.portable_tgs_replay import read_json, verified_file
|
||||
from k1link.sessions.media import RecordedMediaEpoch, RecordedMediaInspector, RecordedMediaSegment
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
_COMPOSITION = r"^ai-composition-[a-f0-9]{64}$"
|
||||
BUILD_PREFIX = "/api/v1/laboratory/replay-builds"
|
||||
|
||||
|
||||
class BuildMember(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
bundle_sha256: str = Field(pattern=SHA)
|
||||
view: dict[str, Any]
|
||||
|
||||
|
||||
class ReplayBuildPlan(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
schema_version: str = Field(pattern=r"^missioncore.replay-build/v1$")
|
||||
result_id: str = Field(pattern=_COMPOSITION)
|
||||
source_session_id: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$")
|
||||
base_sha256: str = Field(pattern=SHA)
|
||||
cache_key: str = Field(pattern=SHA)
|
||||
members: list[BuildMember] = Field(min_length=1, max_length=128)
|
||||
files: dict[str, int] = Field(min_length=1, max_length=100000)
|
||||
|
||||
def validate_references(self) -> None:
|
||||
if any(
|
||||
re.fullmatch(SHA, sha) is None or not 0 < size <= MAX_REPLAY_BYTES
|
||||
for sha, size in self.files.items()
|
||||
):
|
||||
raise ValueError("Invalid replay input identity or size")
|
||||
if self.base_sha256 not in self.files:
|
||||
raise ValueError("Missing base recording")
|
||||
ids = [member.view.get("result_id") for member in self.members]
|
||||
if any(not isinstance(key, str) for key in ids) or len(ids) != len(set(ids)):
|
||||
raise ValueError("Duplicate or missing members")
|
||||
for member in self.members:
|
||||
if member.bundle_sha256 not in self.files:
|
||||
raise ValueError("Missing source contract")
|
||||
if member.view.get("source_session_id") != self.source_session_id:
|
||||
raise ValueError("Member belongs to another source")
|
||||
for artifact in member.view["artifacts"]:
|
||||
if self.files.get(artifact["sha256"]) != artifact["byte_length"]:
|
||||
raise ValueError("Missing result artifact")
|
||||
|
||||
|
||||
class BuildInputs:
|
||||
"""Minimal renderer adapter; no copied SessionStore or operator database."""
|
||||
|
||||
def __init__(self, plan: ReplayBuildPlan, folder: Path):
|
||||
self.plan, self.folder = plan, folder
|
||||
self.artifacts = self
|
||||
|
||||
def object_path(self, digest: str) -> Path:
|
||||
if digest not in self.plan.files:
|
||||
raise ValueError("Unbound replay input")
|
||||
path = self.folder / digest
|
||||
if path.resolve() != path.absolute():
|
||||
raise ValueError("Linked replay input")
|
||||
if digest == self.plan.base_sha256:
|
||||
checked_file(path, digest, self.plan.files[digest])
|
||||
return path
|
||||
return verified_file(path, digest, self.plan.files[digest])
|
||||
|
||||
def read(self, result_id: str) -> dict[str, Any]:
|
||||
return next(
|
||||
member.view for member in self.plan.members if member.view["result_id"] == result_id
|
||||
)
|
||||
|
||||
def member_inputs(self, view: dict[str, Any]) -> tuple[str, RecordedMediaEpoch]:
|
||||
member = next(m for m in self.plan.members if m.view["result_id"] == view["result_id"])
|
||||
bundle = read_json(self.object_path(member.bundle_sha256), 32 * 1024**2)
|
||||
if bundle["source_session_id"] != self.plan.source_session_id:
|
||||
raise ValueError("Source contract belongs to another recording")
|
||||
value = bundle["camera"]["epoch"]
|
||||
init = value["init"]
|
||||
segments = tuple(
|
||||
RecordedMediaSegment(path=self.object_path(part["sha256"]), **part)
|
||||
for part in value["segments"]
|
||||
)
|
||||
if self.plan.files.get(init["sha256"]) != init["byte_length"] or any(
|
||||
self.plan.files.get(p.sha256) != p.byte_length for p in segments
|
||||
):
|
||||
raise ValueError("Camera contract size mismatch")
|
||||
return member.bundle_sha256, RecordedMediaEpoch(
|
||||
ordinal=value["ordinal"],
|
||||
path=self.folder,
|
||||
init_path=self.object_path(init["sha256"]),
|
||||
init_byte_length=init["byte_length"],
|
||||
init_sha256=init["sha256"],
|
||||
media_type=value["media_type"],
|
||||
timeline_start_seconds=value["timeline_start_seconds"],
|
||||
timeline_end_seconds=value["timeline_end_seconds"],
|
||||
segments=segments,
|
||||
)
|
||||
|
||||
|
||||
class ReplayBuilds:
|
||||
def __init__(self, publications: ReplayPublications, ffmpeg: Path):
|
||||
self.publications, self.ffmpeg = publications, ffmpeg
|
||||
self.root = publications.runtime / "presentation" / "replay-builds"
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
# A process restart releases old leases. Resume the same sealed plan.
|
||||
for path in self.root.glob("ai-composition-*/state.json"):
|
||||
row = read_json(path, 8192)
|
||||
folder = self.directory(path.parent.name)
|
||||
self.plan(path.parent.name) # Establish ownership before retiring crash scratch.
|
||||
for partial in (folder / "inputs").glob(".upload-*"):
|
||||
if (re.fullmatch(r"\.upload-[a-z0-9_]{8}", partial.name)
|
||||
and partial.resolve() == partial.absolute() and partial.is_file()):
|
||||
partial.unlink()
|
||||
if row.get("state") == "building":
|
||||
_write(path, {**row, "state": "queued"})
|
||||
|
||||
def directory(self, result_id: str) -> Path:
|
||||
if re.fullmatch(_COMPOSITION, result_id) is None:
|
||||
raise ValueError("Invalid build owner")
|
||||
self.publications.require_alive(result_id)
|
||||
folder = self.root / result_id
|
||||
if folder.absolute() != folder.resolve():
|
||||
raise ValueError("Linked build directory")
|
||||
return folder
|
||||
|
||||
def plan(self, result_id: str) -> ReplayBuildPlan:
|
||||
path = self.directory(result_id) / "plan.json"
|
||||
return ReplayBuildPlan.model_validate(read_json(path, 8 * 1024**2))
|
||||
|
||||
def status(self, result_id: str) -> dict[str, Any]:
|
||||
path = self.directory(result_id) / "state.json"
|
||||
if not path.exists():
|
||||
raise FileNotFoundError("Replay build has not been admitted")
|
||||
return read_json(path, 8192)
|
||||
|
||||
def register(self, plan: ReplayBuildPlan) -> dict[str, Any]:
|
||||
plan.validate_references()
|
||||
with LOCK:
|
||||
folder = self.directory(plan.result_id)
|
||||
path = folder / "plan.json"
|
||||
if path.exists():
|
||||
if self.plan(plan.result_id) != plan:
|
||||
raise ValueError("Build identity is immutable")
|
||||
else:
|
||||
# Reserve for declared inputs of all admitted, unfinished builds.
|
||||
pending = sum(
|
||||
sum(self.plan(p.parent.name).files.values())
|
||||
for p in self.root.glob("*/plan.json")
|
||||
if self.status(p.parent.name)["state"] != "ready"
|
||||
)
|
||||
if (
|
||||
shutil.disk_usage(self.root).free
|
||||
< 40 * 1024**3 + pending + sum(plan.files.values()) + 2 * MAX_REPLAY_BYTES
|
||||
):
|
||||
raise ValueError("Worker replay staging reserve reached")
|
||||
folder.mkdir()
|
||||
_write(path, plan.model_dump())
|
||||
_write(folder / "state.json", {"state": "receiving", "attempts": 0})
|
||||
state = self.status(plan.result_id)
|
||||
missing = (
|
||||
[]
|
||||
if state["state"] == "ready"
|
||||
else [sha for sha in plan.files if not (folder / "inputs" / sha).is_file()]
|
||||
)
|
||||
return {**state, "missing": missing}
|
||||
|
||||
def commit(self, result_id: str, *, retry: bool = False) -> dict[str, Any]:
|
||||
with LOCK:
|
||||
state = self.status(result_id)
|
||||
if state["state"] in {"queued", "building", "ready"}:
|
||||
return state
|
||||
if state["state"] == "failed" and not retry:
|
||||
return state
|
||||
if self.publications.active[result_id]:
|
||||
raise ValueError("Replay input transfer is still active")
|
||||
plan = self.plan(result_id)
|
||||
inputs = BuildInputs(plan, self.directory(result_id) / "inputs")
|
||||
for sha in plan.files:
|
||||
inputs.object_path(sha)
|
||||
# Validate the source bindings before admitting an expensive render.
|
||||
for member in plan.members:
|
||||
inputs.member_inputs(member.view)
|
||||
state = {"state": "queued", "attempts": state["attempts"]}
|
||||
_write(self.directory(result_id) / "state.json", state)
|
||||
return state
|
||||
|
||||
def run_once(self) -> None:
|
||||
for path in sorted(self.root.glob("ai-composition-*/state.json")):
|
||||
result_id = path.parent.name
|
||||
with LOCK:
|
||||
state = self.status(result_id)
|
||||
if state["state"] != "queued":
|
||||
continue
|
||||
self.publications.active[result_id] += 1
|
||||
_write(path, {"state": "building", "attempts": state["attempts"] + 1})
|
||||
try:
|
||||
self.build(result_id)
|
||||
except Exception as exc:
|
||||
_LOG.exception("Worker full replay assembly failed for %s", result_id)
|
||||
with LOCK:
|
||||
_write(
|
||||
path,
|
||||
{
|
||||
"state": "failed",
|
||||
"attempts": state["attempts"] + 1,
|
||||
"error": str(exc)[:1500],
|
||||
},
|
||||
)
|
||||
finally:
|
||||
with LOCK:
|
||||
self.publications.active[result_id] -= 1
|
||||
return # One build per pass; bounded single Worker consumer.
|
||||
|
||||
def build(self, result_id: str) -> None:
|
||||
plan = self.plan(result_id)
|
||||
folder = self.directory(result_id)
|
||||
try:
|
||||
manifest, _ = self.publications.read(result_id, plan.base_sha256)
|
||||
if manifest.cache_key != plan.cache_key:
|
||||
raise ValueError("Published build key changed")
|
||||
except FileNotFoundError:
|
||||
inputs = BuildInputs(plan, folder / "inputs")
|
||||
service = PortableReplayService(
|
||||
view=cast(PortableResultViewService, inputs),
|
||||
data_dir=folder / "assembly",
|
||||
media=RecordedMediaInspector(),
|
||||
recording_source=lambda _: (inputs.object_path(plan.base_sha256), plan.base_sha256),
|
||||
ffmpeg_path=self.ffmpeg,
|
||||
member_inputs=inputs.member_inputs,
|
||||
)
|
||||
members = tuple(m.view["result_id"] for m in plan.members)
|
||||
key, _ = service._composition_key(result_id, members, plan.base_sha256)
|
||||
if key != plan.cache_key:
|
||||
raise ValueError("Renderer identity mismatch") from None
|
||||
artifact = service.prepare_composition(result_id, members, plan.base_sha256)
|
||||
manifest = ReplayManifest(
|
||||
schema_version="missioncore.ready-lab-replay/v1",
|
||||
result_id=result_id,
|
||||
base_sha256=plan.base_sha256,
|
||||
cache_key=key,
|
||||
sha256=artifact.sha256,
|
||||
byte_length=artifact.byte_length,
|
||||
)
|
||||
self.publications.publish(manifest, artifact.path)
|
||||
with LOCK:
|
||||
# The publication is now the durable product; only this job's scratch retires.
|
||||
for name in ("inputs", "assembly"):
|
||||
target = folder / name
|
||||
if target.exists():
|
||||
if target.resolve() != target.absolute():
|
||||
raise ValueError("Linked build scratch")
|
||||
shutil.rmtree(target)
|
||||
_write(
|
||||
folder / "state.json",
|
||||
{
|
||||
"state": "ready",
|
||||
"attempts": self.status(result_id)["attempts"],
|
||||
"manifest": manifest.model_dump(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def build_replay_build_router(builds: ReplayBuilds) -> APIRouter:
|
||||
router = APIRouter()
|
||||
|
||||
@router.post(BUILD_PREFIX)
|
||||
def register(plan: ReplayBuildPlan) -> dict[str, Any]:
|
||||
try:
|
||||
return builds.register(plan)
|
||||
except (ValueError, OSError, KeyError) as exc:
|
||||
raise HTTPException(409, "Replay assembly admission failed") from exc
|
||||
|
||||
@router.get(BUILD_PREFIX + "/{result_id}")
|
||||
def status(result_id: str) -> dict[str, Any]:
|
||||
try:
|
||||
return builds.status(result_id)
|
||||
except FileNotFoundError as exc:
|
||||
raise HTTPException(404, "Replay assembly has not been admitted") from exc
|
||||
except (ValueError, OSError) as exc:
|
||||
raise HTTPException(409, "Replay assembly unavailable") from exc
|
||||
|
||||
@router.put(BUILD_PREFIX + "/{result_id}/inputs/{digest}")
|
||||
async def upload(result_id: str, digest: str, request: Request) -> dict[str, Any]:
|
||||
with LOCK:
|
||||
plan = builds.plan(result_id)
|
||||
state = builds.status(result_id)
|
||||
if digest not in plan.files or state["state"] != "receiving":
|
||||
raise HTTPException(409, "Input is not awaiting transfer")
|
||||
if int(request.headers.get("content-length", "-1")) != plan.files[digest]:
|
||||
raise HTTPException(413, "Input length mismatch")
|
||||
directory = builds.directory(result_id) / "inputs"
|
||||
if directory.resolve() != directory.absolute():
|
||||
raise HTTPException(409, "Linked replay staging")
|
||||
directory.mkdir(exist_ok=True)
|
||||
builds.publications.active[result_id] += 1
|
||||
import tempfile
|
||||
|
||||
partial: Path | None = None
|
||||
try:
|
||||
fd, name = tempfile.mkstemp(prefix=".upload-", dir=directory)
|
||||
partial = Path(name)
|
||||
total, hasher, started = 0, hashlib.sha256(), time.monotonic()
|
||||
with os.fdopen(fd, "wb") as stream:
|
||||
async for chunk in request.stream():
|
||||
total += len(chunk)
|
||||
if total > plan.files[digest] or time.monotonic() - started > 1800:
|
||||
raise HTTPException(413, "Input transfer exceeded bounds")
|
||||
hasher.update(chunk)
|
||||
stream.write(chunk)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
if total != plan.files[digest] or hasher.hexdigest() != digest:
|
||||
raise HTTPException(422, "Input checksum mismatch")
|
||||
with LOCK:
|
||||
builds.publications.require_alive(result_id)
|
||||
os.replace(partial, directory / digest)
|
||||
return {"sha256": digest, "byte_length": total}
|
||||
finally:
|
||||
if partial is not None:
|
||||
partial.unlink(missing_ok=True)
|
||||
with LOCK:
|
||||
builds.publications.active[result_id] -= 1
|
||||
|
||||
@router.post(BUILD_PREFIX + "/{result_id}/commit")
|
||||
def commit(result_id: str, retry: bool = False) -> dict[str, Any]:
|
||||
try:
|
||||
return builds.commit(result_id, retry=retry)
|
||||
except (ValueError, OSError, KeyError) as exc:
|
||||
raise HTTPException(409, "Replay inputs failed verification") from exc
|
||||
|
||||
return router
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from contextlib import asynccontextmanager
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
@@ -23,6 +25,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_build import BUILD_PREFIX, ReplayBuilds, build_replay_build_router
|
||||
from k1link.laboratory.replay_publication import ReplayPublications
|
||||
from k1link.laboratory.worker_gateway import LaboratoryGatewayConfiguration
|
||||
from k1link.laboratory.worker_recorded_sources import (
|
||||
@@ -75,11 +78,26 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
surface_reader = K1LocalSurfaceReadService()
|
||||
ready_replays = ReplayPublications(root)
|
||||
replay_builds = ReplayBuilds(ready_replays, ffmpeg)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
yield
|
||||
surface_reader.close()
|
||||
stop = asyncio.Event()
|
||||
async def build_loop():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
await asyncio.to_thread(replay_builds.run_once)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Replay build queue pass failed")
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(stop.wait(), timeout=2)
|
||||
task = asyncio.create_task(build_loop())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
stop.set()
|
||||
await task
|
||||
surface_reader.close()
|
||||
|
||||
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
||||
|
||||
@@ -89,7 +107,10 @@ def create_app() -> FastAPI:
|
||||
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:
|
||||
upload = (request.method == "PUT" and request.url.path.startswith(BUILD_PREFIX + "/")
|
||||
and "/inputs/" in request.url.path)
|
||||
limit = 1024**3 if upload else 8 * 1024**2
|
||||
if length is None or not length.isdecimal() or int(length) > limit:
|
||||
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):
|
||||
@@ -163,6 +184,7 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
)
|
||||
app.include_router(build_ready_replay_router(ready_replays))
|
||||
app.include_router(build_replay_build_router(replay_builds))
|
||||
if ffmpeg.is_file():
|
||||
app.include_router(build_worker_laboratory_presentation(root, ffmpeg))
|
||||
return app
|
||||
|
||||
Reference in New Issue
Block a user