Assemble complete modular LAB recordings on Worker before readiness
This commit is contained in:
@@ -193,8 +193,33 @@ validating Range, ETag, length, RRF2 and SHA-256 before atomic publication. This
|
||||
is in-process retry, not persistent resume after a Core crash.
|
||||
|
||||
Acceptance on 10 November backfilled the three current accepted RRDs unchanged.
|
||||
Future executor completion is **not yet automatically wired** to this publication
|
||||
API. Preserve that distinction when introducing a new producer.
|
||||
New composition runs now opt into `worker-ready-v1`; legacy runs are not enrolled
|
||||
or rebuilt. The existing Core result reconciler waits for all selected module
|
||||
results, submits a digest-bound `missioncore.replay-build/v1` plan and streams
|
||||
only missing inputs from existing stores. It does not render the new LAB on Mac.
|
||||
A previously published canonical source is restored after Core restart without
|
||||
starting a source exporter. A missing canonical source blocks assembly explicitly.
|
||||
|
||||
The authenticated `/api/v1/laboratory/replay-builds` API registers immutable plans;
|
||||
`/{id}/inputs/{sha}` accepts bounded, hash-verified input streams, and
|
||||
`/{id}/commit` validates the source/member bindings before queueing. Only this
|
||||
input route admits up to 1 GiB per file; other request bodies retain the 8 MiB
|
||||
limit. A single consumer in the existing LAB container runs the existing RRD
|
||||
renderer with the bound FFmpeg asset. No separate model runtime is installed.
|
||||
|
||||
Durable plans/state live under `/lab/presentation/replay-builds/<composition-id>`.
|
||||
An interrupted build resumes after service restart. A successful build publishes
|
||||
the immutable full RRD, then removes only its own input and assembly directories.
|
||||
Active upload/build leases protect it from concurrent full-LAB deletion. Explicit
|
||||
LAB deletion also inventories these owned staging files. No model/source TTL applies.
|
||||
Admission reserves 40 GiB plus declared pending inputs and render headroom.
|
||||
|
||||
Core reports the composition ready only after checking the actual Worker replay
|
||||
manifest. Viewing a new run restores that ready RRD; a missing publication cannot
|
||||
fall back to local assembly. Transport retries are bounded; a failed assembly can
|
||||
be retried via `POST /api/v1/observatory/ai-composition-runs/{id}/retry-replay`
|
||||
without rerunning inference. Core keeps only the small publication receipt and
|
||||
its ordinary, unpinned/pinned local viewing cache under existing storage rules.
|
||||
|
||||
For non-destructive cold-view acceptance only, `MISSIONCORE_LAB_VIEW_CACHE_DIR`
|
||||
redirects the portable cache and its local-copy index to an owned empty test root.
|
||||
|
||||
@@ -625,3 +625,35 @@ and unowned interrupted payloads remain separate ownership work; no global
|
||||
recursive cleanup or new age-based purge has been introduced.
|
||||
|
||||
Evidence and exact measured cleanup: [9 November closeout](../outputs/lab-source-lifecycle-20261109/REPORT.md).
|
||||
|
||||
|
||||
## Automatic complete LAB assembly — 10 November 2026
|
||||
|
||||
New `worker-ready-v1` compositions become ready only after their full immutable
|
||||
RRD is published on Worker. Existing accepted compositions are not enrolled or
|
||||
rebuilt. Core's existing result reconciliation submits the source/member digest
|
||||
plan and streams missing inputs from existing stores without transfer duplicates.
|
||||
The current module-result publication/CAS path is preserved; this change moves
|
||||
full-recording rendering, not every existing result transport, off the operator.
|
||||
|
||||
`presentation/replay-builds/<composition-id>` on the bound LAB volume owns only
|
||||
that build's `inputs`, `assembly`, plan and state. Single-consumer assembly uses
|
||||
the existing renderer and FFmpeg runtime. Immutable publication precedes removal
|
||||
of input/assembly scratch. Active transfer/build leases block explicit deletion;
|
||||
startup resumes interrupted builds and retires only identifiable upload partials
|
||||
in verified owned build directories. Models, source recordings and unrelated LABs
|
||||
are outside this cleanup. Failed jobs retain their retry inputs until recovery or
|
||||
explicit owner deletion; they are not silently discarded by age.
|
||||
|
||||
The complete product stays under `presentation/portable-replays`; the operator
|
||||
downloads that file into its ordinary viewing cache with size/SHA verification.
|
||||
New compositions never fall back to local full-RRD assembly. Existing local-copy
|
||||
expiry and pin rules apply only to viewing copies. Restore after Core restart
|
||||
reads a previously published canonical source package without invoking an exporter.
|
||||
Missing canonical preparation remains an explicit prerequisite failure.
|
||||
|
||||
Acceptance: a new short JA composition with DDRNet and TRAVEL TGS published
|
||||
12,780,813 bytes before any view request. GUI download from zero local product
|
||||
bytes, playback, seeking and both layer toggles passed. Existing accepted LABs
|
||||
and their pins were preserved. Evidence, limits and release identities:
|
||||
[Worker assembly report](../outputs/lab-worker-assembly-20261110/REPORT.md).
|
||||
|
||||
@@ -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,10 +78,25 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
surface_reader = K1LocalSurfaceReadService()
|
||||
ready_replays = ReplayPublications(root)
|
||||
replay_builds = ReplayBuilds(ready_replays, ffmpeg)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
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
|
||||
|
||||
@@ -32,6 +32,7 @@ class CompositionRun:
|
||||
setup_ids: tuple[str, ...]
|
||||
job_ids: tuple[str, ...]
|
||||
created_at_utc: str
|
||||
replay_policy: str | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if _RUN.fullmatch(self.run_id) is None:
|
||||
@@ -54,11 +55,14 @@ class CompositionRun:
|
||||
or len(set(self.job_ids)) != len(self.job_ids)
|
||||
):
|
||||
raise CompositionRunError("invalid composition run members")
|
||||
if self.replay_policy not in (None, "worker-ready-v1"):
|
||||
raise CompositionRunError("invalid replay publication policy")
|
||||
if not self.created_at_utc.endswith("Z"):
|
||||
raise CompositionRunError("composition run timestamp must be UTC")
|
||||
|
||||
def as_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
**({"replay_policy": self.replay_policy} if self.replay_policy else {}),
|
||||
"schema_version": RUN_SCHEMA,
|
||||
"run_id": self.run_id,
|
||||
"source_session_id": self.source_session_id,
|
||||
@@ -87,6 +91,7 @@ class CompositionRunStore:
|
||||
job_ids: tuple[str, ...],
|
||||
idempotency_key: str,
|
||||
created_at_utc: str,
|
||||
replay_policy: str | None = None,
|
||||
) -> CompositionRun:
|
||||
digest = hashlib.sha256(
|
||||
canonical_bytes(
|
||||
@@ -109,6 +114,7 @@ class CompositionRunStore:
|
||||
setup_ids=setup_ids,
|
||||
job_ids=job_ids,
|
||||
created_at_utc=created_at_utc,
|
||||
replay_policy=replay_policy,
|
||||
)
|
||||
destination = self.root / f"{run.run_id}.json"
|
||||
payload = canonical_bytes(run.as_dict())
|
||||
@@ -260,7 +266,7 @@ def _decode(value: object) -> CompositionRun:
|
||||
}
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or set(value) != keys
|
||||
or set(value) - {"replay_policy"} != keys
|
||||
or value.get("schema_version") != RUN_SCHEMA
|
||||
):
|
||||
raise CompositionRunError("invalid composition run document")
|
||||
@@ -279,4 +285,5 @@ def _decode(value: object) -> CompositionRun:
|
||||
setup_ids=tuple(cast(list[str], row["setup_ids"])),
|
||||
job_ids=tuple(cast(list[str], row["job_ids"])),
|
||||
created_at_utc=cast(str, row["created_at_utc"]),
|
||||
replay_policy=cast(str | None, row.get("replay_policy")),
|
||||
)
|
||||
|
||||
@@ -73,6 +73,8 @@ class PortableReplayService:
|
||||
ffmpeg_path: Path,
|
||||
local_copies: LocalPresentations | None = None,
|
||||
remote_replays: WorkerReplayRestore | None = None,
|
||||
member_inputs: Callable[[dict[str, Any]], tuple[str, RecordedMediaEpoch]] | None = None,
|
||||
worker_required: Callable[[str], bool] | None = None,
|
||||
) -> None:
|
||||
self.view = view
|
||||
self.data_dir = data_dir
|
||||
@@ -82,6 +84,8 @@ class PortableReplayService:
|
||||
self.cache = (local_copies.root if local_copies else
|
||||
data_dir / "observatory-portable-replay-cache")
|
||||
self.remote_replays = remote_replays
|
||||
self.member_inputs = member_inputs
|
||||
self.worker_required = worker_required or (lambda _: False)
|
||||
self.local_copies = local_copies
|
||||
self._verified: OrderedDict[tuple[Path, str], tuple[int, ...]] = OrderedDict()
|
||||
|
||||
@@ -343,6 +347,8 @@ class PortableReplayService:
|
||||
if self.local_copies is not None:
|
||||
self.local_copies.register(run_id, restored, self.cache / f"{key}.json")
|
||||
return restored
|
||||
if self.worker_required(run_id):
|
||||
raise PortableReplayError("Full recording has not been published by Worker")
|
||||
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:
|
||||
@@ -354,29 +360,7 @@ class PortableReplayService:
|
||||
object_rows: list[Any] = []
|
||||
for view in views:
|
||||
result_id = cast(str, view["result_id"])
|
||||
binding = self.view.sessions.get_lab_instance(result_id)
|
||||
if binding is None or binding.source_session_id != source_session_id:
|
||||
raise PortableReplayError("composition result binding disappeared")
|
||||
source = binding.provenance["source"]
|
||||
bundle_sha = source["bundle_sha256"]
|
||||
if not isinstance(bundle_sha, str) or _SHA.fullmatch(bundle_sha) is None:
|
||||
raise PortableReplayError("composition source bundle identity is invalid")
|
||||
bundle_path = (
|
||||
self.data_dir / PORTABLE_SOURCE_DOCUMENT_DIRECTORY / f"{bundle_sha}.json"
|
||||
)
|
||||
bundle = read_json(bundle_path, 32 * 1024 * 1024)
|
||||
verified_file(bundle_path, bundle_sha, bundle_path.stat().st_size)
|
||||
if bundle["source_session_id"] != source_session_id:
|
||||
raise PortableReplayError("composition member belongs to another session")
|
||||
_, catalog_sha = self.view.sessions.get_session_with_catalog_snapshot(
|
||||
source_session_id
|
||||
)
|
||||
if (
|
||||
catalog_sha != source["catalog_sha256"]
|
||||
or catalog_sha != bundle["source_catalog_sha256"]
|
||||
):
|
||||
raise PortableReplayError("composition source catalog changed")
|
||||
member_epoch = self._camera(source_session_id, bundle)
|
||||
bundle_sha, member_epoch = self.resolve_member_inputs(view)
|
||||
if epoch is None:
|
||||
epoch = member_epoch
|
||||
elif (
|
||||
@@ -477,6 +461,36 @@ class PortableReplayService:
|
||||
self.local_copies.register(run_id, artifact, self.cache / f"{key}.json")
|
||||
return artifact
|
||||
|
||||
def resolve_member_inputs(self, view: dict[str, Any]) -> tuple[str, RecordedMediaEpoch]:
|
||||
"""Resolve a sealed source generation; Worker supplies the same contract by digest."""
|
||||
if self.member_inputs is not None:
|
||||
return self.member_inputs(view)
|
||||
source_session_id = view["source_session_id"]
|
||||
result_id = view["result_id"]
|
||||
binding = self.view.sessions.get_lab_instance(result_id)
|
||||
if binding is None or binding.source_session_id != source_session_id:
|
||||
raise PortableReplayError("composition result binding disappeared")
|
||||
source = binding.provenance["source"]
|
||||
bundle_sha = source["bundle_sha256"]
|
||||
if not isinstance(bundle_sha, str) or _SHA.fullmatch(bundle_sha) is None:
|
||||
raise PortableReplayError("composition source bundle identity is invalid")
|
||||
bundle_path = (
|
||||
self.data_dir / PORTABLE_SOURCE_DOCUMENT_DIRECTORY / f"{bundle_sha}.json"
|
||||
)
|
||||
bundle = read_json(bundle_path, 32 * 1024 * 1024)
|
||||
verified_file(bundle_path, bundle_sha, bundle_path.stat().st_size)
|
||||
if bundle["source_session_id"] != source_session_id:
|
||||
raise PortableReplayError("composition member belongs to another session")
|
||||
_, catalog_sha = self.view.sessions.get_session_with_catalog_snapshot(
|
||||
source_session_id
|
||||
)
|
||||
if (
|
||||
catalog_sha != source["catalog_sha256"]
|
||||
or catalog_sha != bundle["source_catalog_sha256"]
|
||||
):
|
||||
raise PortableReplayError("composition source catalog changed")
|
||||
return bundle_sha, self._camera(source_session_id, bundle)
|
||||
|
||||
def _camera(self, session_id: str, bundle: dict[str, Any]) -> RecordedMediaEpoch:
|
||||
camera = bundle["camera"]
|
||||
artifact = self.view.sessions.get_recorded_media(session_id, camera["artifact_id"])
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Operator control plane for Worker-owned full-recording publication.
|
||||
|
||||
Transfers existing admitted inputs without making local working copies. No renderer,
|
||||
FFmpeg, model or RRD assembly runs here. Only new, explicitly enrolled runs are visited.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
import httpx
|
||||
|
||||
from k1link.laboratory.data_deletion import _write
|
||||
from k1link.laboratory.replay_build import BUILD_PREFIX, BuildMember, ReplayBuildPlan
|
||||
from k1link.laboratory.replay_publication import ReplayManifest
|
||||
from k1link.laboratory.worker_gateway import LaboratoryGatewayConfiguration
|
||||
from k1link.observatory.composition_runs import CompositionRun, CompositionRunStore
|
||||
from k1link.observatory.portable_replay import PortableReplayService
|
||||
from k1link.observatory.portable_tgs_replay import read_json
|
||||
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
|
||||
from k1link.observatory.source_admission import PORTABLE_SOURCE_DOCUMENT_DIRECTORY
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ReplayFinalization:
|
||||
def __init__(
|
||||
self,
|
||||
runs: CompositionRunStore,
|
||||
queue: ObservatoryRecordedJobQueue,
|
||||
replay: PortableReplayService,
|
||||
configuration: LaboratoryGatewayConfiguration,
|
||||
*,
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
) -> None:
|
||||
self.runs, self.queue, self.replay = runs, queue, replay
|
||||
self.configuration, self.transport = configuration, transport
|
||||
self.root = runs.root / "replay-publication"
|
||||
self.root.mkdir(exist_ok=True)
|
||||
|
||||
def required(self, result_id: str) -> bool:
|
||||
return self.runs.get(result_id).replay_policy == "worker-ready-v1"
|
||||
|
||||
def status(self, run_id: str) -> dict[str, Any]:
|
||||
self.runs.get(run_id)
|
||||
path = self.root / (run_id + ".json")
|
||||
return read_json(path, 16384) if path.exists() else {"state": "pending", "attempts": 0}
|
||||
|
||||
def client(self) -> httpx.Client:
|
||||
return httpx.Client(
|
||||
base_url=self.configuration.base_url,
|
||||
transport=self.transport,
|
||||
timeout=httpx.Timeout(120, connect=5),
|
||||
trust_env=False,
|
||||
follow_redirects=False,
|
||||
headers={"Authorization": "Bearer " + self.configuration.token()},
|
||||
)
|
||||
|
||||
def retry(self, run_id: str) -> dict[str, Any]:
|
||||
if not self.required(run_id):
|
||||
raise ValueError("Legacy LAB has no automatic assembly job")
|
||||
state = self.status(run_id)
|
||||
if state["state"] == "ready":
|
||||
return state
|
||||
with self.client() as client:
|
||||
response = client.get(BUILD_PREFIX + "/" + run_id)
|
||||
if response.status_code == 200 and response.json()["state"] == "failed":
|
||||
response = client.post(
|
||||
BUILD_PREFIX + "/" + run_id + "/commit?retry=true", content=b""
|
||||
)
|
||||
if response.status_code != 404:
|
||||
response.raise_for_status()
|
||||
_write(self.root / (run_id + ".json"), {"state": "pending", "attempts": 0})
|
||||
return self.status(run_id)
|
||||
|
||||
def inputs(
|
||||
self, run: CompositionRun, members: tuple[str, ...]
|
||||
) -> tuple[ReplayBuildPlan, dict[str, Path]]:
|
||||
base = self.replay.recording_source(run.source_session_id)
|
||||
if base is None:
|
||||
raise ValueError("Canonical source recording is not prepared")
|
||||
files = {base[1]: base[0]}
|
||||
key, views = self.replay._composition_key(run.run_id, members, base[1])
|
||||
member_plans = []
|
||||
for view in views:
|
||||
bundle_sha, epoch = self.replay.resolve_member_inputs(view)
|
||||
files[bundle_sha] = (
|
||||
self.replay.data_dir / PORTABLE_SOURCE_DOCUMENT_DIRECTORY / (bundle_sha + ".json")
|
||||
)
|
||||
files[epoch.init_sha256] = epoch.init_path
|
||||
for segment in epoch.segments:
|
||||
files[segment.sha256] = segment.path
|
||||
for artifact in view["artifacts"]:
|
||||
files[artifact["sha256"]] = self.replay.view.artifacts.object_path(
|
||||
artifact["sha256"]
|
||||
)
|
||||
member_plans.append(BuildMember(bundle_sha256=bundle_sha, view=view))
|
||||
plan = ReplayBuildPlan(
|
||||
schema_version="missioncore.replay-build/v1",
|
||||
result_id=run.run_id,
|
||||
source_session_id=run.source_session_id,
|
||||
base_sha256=base[1],
|
||||
cache_key=key,
|
||||
members=member_plans,
|
||||
files={sha: path.stat().st_size for sha, path in files.items()},
|
||||
)
|
||||
plan.validate_references()
|
||||
return plan, files
|
||||
|
||||
def step(self, run: CompositionRun, members: tuple[str, ...]) -> dict[str, Any]:
|
||||
prefix = BUILD_PREFIX + "/" + run.run_id
|
||||
with self.client() as client:
|
||||
response = client.get(prefix)
|
||||
if response.status_code == 404:
|
||||
state = {"state": "receiving"}
|
||||
else:
|
||||
response.raise_for_status()
|
||||
state = response.json()
|
||||
if state["state"] == "receiving":
|
||||
plan, files = self.inputs(run, members)
|
||||
response = client.post(BUILD_PREFIX, json=plan.model_dump())
|
||||
response.raise_for_status()
|
||||
state = response.json()
|
||||
for sha in state["missing"]:
|
||||
path = files[sha]
|
||||
if path.is_symlink():
|
||||
raise ValueError("Linked replay input")
|
||||
# Stream the already-existing file, never create a transfer duplicate.
|
||||
with path.open("rb") as incoming:
|
||||
response = client.put(
|
||||
prefix + "/inputs/" + sha,
|
||||
content=incoming,
|
||||
headers={"Content-Length": str(plan.files[sha])},
|
||||
)
|
||||
response.raise_for_status()
|
||||
response = client.post(prefix + "/commit", content=b"")
|
||||
response.raise_for_status()
|
||||
state = response.json()
|
||||
if state["state"] == "ready":
|
||||
manifest = ReplayManifest.model_validate(state["manifest"])
|
||||
base = self.replay.recording_source(run.source_session_id)
|
||||
if base is None:
|
||||
raise ValueError("Canonical source no longer available")
|
||||
key, _ = self.replay._composition_key(run.run_id, members, base[1])
|
||||
if (manifest.result_id, manifest.base_sha256, manifest.cache_key) != (
|
||||
run.run_id,
|
||||
base[1],
|
||||
key,
|
||||
):
|
||||
raise ValueError("Worker published an unrelated recording")
|
||||
# Read the actual immutable publication, not just a task-success flag.
|
||||
response = client.get(f"/api/v1/laboratory/portable-replays/{run.run_id}/{base[1]}")
|
||||
response.raise_for_status()
|
||||
if ReplayManifest.model_validate(response.json()) != manifest:
|
||||
raise ValueError("Worker publication generation changed")
|
||||
return cast(dict[str, Any], state)
|
||||
|
||||
def run_once(self) -> None:
|
||||
for run in self.runs.list(include_hidden=False):
|
||||
if run.replay_policy != "worker-ready-v1":
|
||||
continue
|
||||
previous = self.status(run.run_id)
|
||||
if (
|
||||
previous["state"] in {"ready", "failed"}
|
||||
or previous.get("retry_after", 0) > time.time()
|
||||
):
|
||||
continue
|
||||
jobs = [self.queue.get(key) for key in run.job_ids]
|
||||
if not all(
|
||||
j.state == "succeeded" and j.publication_state == "published" and j.result_id
|
||||
for j in jobs
|
||||
):
|
||||
continue
|
||||
attempts = previous.get("attempts", 0)
|
||||
try:
|
||||
state = self.step(run, tuple(cast(str, j.result_id) for j in jobs))
|
||||
# Transport retry budget is independent of Worker render attempts.
|
||||
state = {**state, "attempts": 0}
|
||||
except (httpx.HTTPError, ValueError, OSError, KeyError) as exc:
|
||||
attempts += 1
|
||||
_LOG.exception("Full replay publication deferred for %s", run.run_id)
|
||||
state = {
|
||||
"state": "failed" if attempts >= 5 else "pending",
|
||||
"attempts": attempts,
|
||||
"retry_after": time.time() + min(300, 15 * 2**attempts),
|
||||
"error": str(exc)[:1500],
|
||||
}
|
||||
_write(self.root / (run.run_id + ".json"), state)
|
||||
+28
-10
@@ -597,6 +597,11 @@ def _m48_recorded_camera_playback_source(
|
||||
def _canonical_lab_recording_source(session_id: str) -> tuple[Path, str] | None:
|
||||
"""Read a ready operator recording for the existing portable result viewer."""
|
||||
snapshot = session_recording_preparation_manager.status(session_id)
|
||||
if snapshot is None:
|
||||
# Restore an already published source after a Core restart. This never
|
||||
# schedules source conversion, media processing or a local renderer.
|
||||
command = operator_session_store.prepare_replay(session_id, speed=1.0, loop=False)
|
||||
snapshot = session_recording_preparation_manager.restore_published(command)
|
||||
if snapshot is None or snapshot.state != "ready" or snapshot.recording is None:
|
||||
return None
|
||||
if snapshot.command.map_version is not None:
|
||||
@@ -747,6 +752,9 @@ async def _portable_result_publication_reconciler() -> None:
|
||||
await asyncio.to_thread(service.run_once)
|
||||
with suppress(OSError, ValueError):
|
||||
await asyncio.to_thread(service.artifact_transport.collect_source_copies)
|
||||
if replay_finalization is not None:
|
||||
with suppress(OSError, ValueError):
|
||||
await asyncio.to_thread(replay_finalization.run_once)
|
||||
await asyncio.sleep(15.0)
|
||||
|
||||
|
||||
@@ -1012,25 +1020,34 @@ lab_deletion_service = LabDeletionCoordinator(
|
||||
)
|
||||
app.include_router(build_local_storage_router(local_presentation_copies))
|
||||
|
||||
replay_finalization = None
|
||||
if session_artifact_gateway is not None and _ffmpeg is not None:
|
||||
app.include_router(
|
||||
build_portable_replay_router(
|
||||
PortableReplayService(
|
||||
replay_service = PortableReplayService(
|
||||
view=PortableResultViewService(
|
||||
sessions=session_store, artifacts=session_artifact_gateway.store
|
||||
),
|
||||
data_dir=session_store.data_dir,
|
||||
media=session_recorded_media_inspector,
|
||||
recording_source=_canonical_lab_recording_source,
|
||||
ffmpeg_path=_ffmpeg,
|
||||
data_dir=session_store.data_dir, media=session_recorded_media_inspector,
|
||||
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,
|
||||
worker_required=lambda key: (
|
||||
OBSERVATORY_AI_COMPOSITION_RUNS.get(key).replay_policy == "worker-ready-v1"
|
||||
if OBSERVATORY_AI_COMPOSITION_RUNS is not None else False
|
||||
),
|
||||
composition_runs=OBSERVATORY_AI_COMPOSITION_RUNS,
|
||||
)
|
||||
if (laboratory_worker_gateway.configuration is not None
|
||||
and OBSERVATORY_AI_COMPOSITION_RUNS is not None
|
||||
and OBSERVATORY_RECORDED_JOB_QUEUE is not None):
|
||||
from k1link.observatory.replay_finalization import ReplayFinalization
|
||||
replay_finalization = ReplayFinalization(
|
||||
OBSERVATORY_AI_COMPOSITION_RUNS, OBSERVATORY_RECORDED_JOB_QUEUE,
|
||||
replay_service, laboratory_worker_gateway.configuration,
|
||||
)
|
||||
app.include_router(build_portable_replay_router(
|
||||
replay_service, composition_runs=OBSERVATORY_AI_COMPOSITION_RUNS,
|
||||
queue=OBSERVATORY_RECORDED_JOB_QUEUE,
|
||||
)
|
||||
)
|
||||
))
|
||||
|
||||
for legacy_router in plugin_environment.legacy_routers:
|
||||
app.include_router(legacy_router)
|
||||
@@ -1112,6 +1129,7 @@ if (
|
||||
queue=OBSERVATORY_RECORDED_JOB_QUEUE,
|
||||
view_profiles=OBSERVATORY_LAB_VIEW_PROFILES,
|
||||
deletion_service=lab_deletion_service,
|
||||
replay_finalization=replay_finalization,
|
||||
)
|
||||
)
|
||||
if OBSERVATORY_WORKER_DISPATCH_READY:
|
||||
|
||||
@@ -37,6 +37,7 @@ from k1link.observatory.recorded_jobs import (
|
||||
ObservatoryRecordedQueueError,
|
||||
ObservatoryRecordedQueueNotFoundError,
|
||||
)
|
||||
from k1link.observatory.replay_finalization import ReplayFinalization
|
||||
from k1link.observatory.source_admission import PortableSourceNotPreparedError
|
||||
from k1link.sessions import SessionNotFoundError, SessionStore
|
||||
|
||||
@@ -122,6 +123,7 @@ def build_modular_observatory_router(
|
||||
queue: ObservatoryRecordedJobQueue | None = None,
|
||||
view_profiles: LabViewProfileStore | None = None,
|
||||
deletion_service=None,
|
||||
replay_finalization: ReplayFinalization | None = None,
|
||||
) -> APIRouter:
|
||||
router = APIRouter()
|
||||
|
||||
@@ -311,12 +313,13 @@ def build_modular_observatory_router(
|
||||
setup_ids=tuple(setup_ids),
|
||||
job_ids=tuple(job.job_id for job in jobs),
|
||||
idempotency_key=request.idempotency_key,
|
||||
replay_policy="worker-ready-v1" if replay_finalization is not None else None,
|
||||
created_at_utc=datetime.now(UTC)
|
||||
.isoformat(timespec="milliseconds")
|
||||
.replace("+00:00", "Z"),
|
||||
)
|
||||
presentation = ontology.project_composition(composition)
|
||||
run_projection = {**run.as_dict(), "presentation": presentation}
|
||||
run_projection = {**public_run(run), "presentation": presentation}
|
||||
except StopIteration:
|
||||
pass
|
||||
except (CompositionRunError, ObservatoryOntologyError) as exc:
|
||||
@@ -343,6 +346,11 @@ def build_modular_observatory_router(
|
||||
},
|
||||
}
|
||||
|
||||
def public_run(run: CompositionRun) -> dict[str, object]:
|
||||
value = run.as_dict()
|
||||
value.pop("replay_policy", None)
|
||||
return value
|
||||
|
||||
def project_run(run: CompositionRun) -> dict[str, object]:
|
||||
if ontology is None:
|
||||
raise CompositionRunError("composition ontology is unavailable")
|
||||
@@ -359,8 +367,14 @@ def build_modular_observatory_router(
|
||||
for job in jobs
|
||||
)
|
||||
failed = any(job.state == "failed" or job.publication_state == "failed" for job in jobs)
|
||||
replay_state = None
|
||||
if exact.replay_policy == "worker-ready-v1":
|
||||
replay_state = (replay_finalization.status(exact.run_id)
|
||||
if replay_finalization else {"state": "pending"})
|
||||
published = published and replay_state["state"] == "ready"
|
||||
failed = failed or replay_state["state"] == "failed"
|
||||
return {
|
||||
**exact.as_dict(),
|
||||
**public_run(exact),
|
||||
"state": "ready" if published else "failed" if failed else "running",
|
||||
"configuration_label": (
|
||||
f"{store.get_session(exact.source_session_id).summary.display_name} · "
|
||||
@@ -372,6 +386,15 @@ def build_modular_observatory_router(
|
||||
"result_ids": [job.result_id for job in jobs if job.result_id is not None],
|
||||
}
|
||||
|
||||
@router.post("/api/v1/observatory/ai-composition-runs/{run_id}/retry-replay")
|
||||
def retry_replay(run_id: str) -> dict[str, Any]:
|
||||
if replay_finalization is None:
|
||||
raise HTTPException(503, "Сборщик записи недоступен.")
|
||||
try:
|
||||
return replay_finalization.retry(run_id)
|
||||
except (ValueError, OSError) as exc:
|
||||
raise HTTPException(409, "Не удалось повторить сборку записи.") from exc
|
||||
|
||||
@router.get("/api/v1/observatory/ai-composition-runs")
|
||||
def composition_run_list(
|
||||
source_session_id: str = Query(
|
||||
|
||||
@@ -506,3 +506,63 @@ def test_composition_prepares_an_unopened_recording_before_submit(tmp_path: Path
|
||||
assert response.status_code == 200
|
||||
assert response.json()["dispatch"]["ready"] is True
|
||||
assert calls == ["check", "prepare-check", "submit"]
|
||||
|
||||
|
||||
def test_new_composition_is_not_ready_until_worker_recording_is_published(tmp_path):
|
||||
registry = ModuleRegistry.from_file(
|
||||
Path(__file__).parents[1] / "config/observatory-ai-modules.json"
|
||||
)
|
||||
tgs = next(m for m in registry.modules if m.module_id == "tgs")
|
||||
composition = registry.compose(
|
||||
{
|
||||
"schema_version": COMPOSITION_SCHEMA,
|
||||
"selections": [
|
||||
{
|
||||
"group": tgs.group,
|
||||
"module_id": tgs.module_id,
|
||||
"module_sha256": tgs.sha256,
|
||||
"parameters": {},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
runs = CompositionRunStore(tmp_path / "runs")
|
||||
run = runs.save(
|
||||
source_session_id="source-1",
|
||||
composition=composition,
|
||||
setup_ids=("setup-1",),
|
||||
job_ids=("job-1",),
|
||||
idempotency_key="new",
|
||||
created_at_utc="2026-11-10T00:00:00Z",
|
||||
replay_policy="worker-ready-v1",
|
||||
)
|
||||
state = {"state": "building"}
|
||||
job = SimpleNamespace(
|
||||
state="succeeded", publication_state="published", result_id="result", as_dict=lambda: {}
|
||||
)
|
||||
app = FastAPI()
|
||||
app.include_router(
|
||||
build_modular_observatory_router(
|
||||
store=SimpleNamespace(
|
||||
get_session=lambda _: SimpleNamespace(
|
||||
summary=SimpleNamespace(display_name="source")
|
||||
)
|
||||
),
|
||||
compositions=ModularCompositionStore(tmp_path / "compositions", registry),
|
||||
composition_runs=runs,
|
||||
queue=SimpleNamespace(get=lambda _: job),
|
||||
ontology=SimpleNamespace(project_module_ids=lambda _: {"configuration_label": "TGS"}),
|
||||
replay_finalization=SimpleNamespace(status=lambda _: state),
|
||||
)
|
||||
)
|
||||
client = TestClient(app)
|
||||
path = "/api/v1/observatory/ai-composition-runs?source_session_id=source-1"
|
||||
row = client.get(path).json()["items"][0]
|
||||
assert row["state"] == "running"
|
||||
# Preserve the existing strict frontend projection contract.
|
||||
assert "replay_policy" not in row and "replay_publication" not in row
|
||||
state["state"] = "failed"
|
||||
assert client.get(path).json()["items"][0]["state"] == "failed"
|
||||
state["state"] = "ready"
|
||||
assert client.get(path).json()["items"][0]["state"] == "ready"
|
||||
assert runs.get(run.run_id).replay_policy == "worker-ready-v1"
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import hashlib
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.laboratory.data_deletion import LabDeletionError, _write
|
||||
from k1link.laboratory.replay_build import (
|
||||
BUILD_PREFIX,
|
||||
BuildMember,
|
||||
ReplayBuildPlan,
|
||||
ReplayBuilds,
|
||||
build_replay_build_router,
|
||||
)
|
||||
from k1link.laboratory.replay_publication import ReplayPublications
|
||||
from k1link.observatory.portable_replay import PortableReplayService
|
||||
from k1link.observatory.portable_tgs_replay import PortableReplayError
|
||||
|
||||
RUN = "ai-composition-" + "a" * 64
|
||||
RESULT = "ai-layer-ddrnet-" + "b" * 64
|
||||
|
||||
|
||||
def fixture(tmp_path):
|
||||
blobs = {}
|
||||
|
||||
def add(value):
|
||||
digest = hashlib.sha256(value).hexdigest()
|
||||
blobs[digest] = value
|
||||
return {"sha256": digest, "byte_length": len(value)}
|
||||
|
||||
base = add(b"RRF2source")
|
||||
init = add(b"init")
|
||||
segment = add(b"frame")
|
||||
bundle = add(
|
||||
json.dumps(
|
||||
{
|
||||
"source_session_id": "source",
|
||||
"camera": {
|
||||
"epoch": {
|
||||
"ordinal": 1,
|
||||
"media_type": "video/mp4",
|
||||
"init": init,
|
||||
"timeline_start_seconds": 0.0,
|
||||
"timeline_end_seconds": 0.1,
|
||||
"segments": [
|
||||
{
|
||||
**segment,
|
||||
"sequence": 1,
|
||||
"random_access": True,
|
||||
"end_time_seconds": 0.1,
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
).encode()
|
||||
)
|
||||
view = {
|
||||
"result_id": RESULT,
|
||||
"source_session_id": "source",
|
||||
"artifacts": [],
|
||||
"artifact_manifest_id": "c" * 64,
|
||||
}
|
||||
service = PortableReplayService(
|
||||
view=SimpleNamespace(read=lambda _: view),
|
||||
data_dir=tmp_path,
|
||||
media=None,
|
||||
recording_source=lambda _: None,
|
||||
ffmpeg_path=tmp_path / "ffmpeg",
|
||||
)
|
||||
key, _ = service._composition_key(RUN, (RESULT,), base["sha256"])
|
||||
plan = ReplayBuildPlan(
|
||||
schema_version="missioncore.replay-build/v1",
|
||||
result_id=RUN,
|
||||
source_session_id="source",
|
||||
base_sha256=base["sha256"],
|
||||
cache_key=key,
|
||||
members=[BuildMember(view=view, bundle_sha256=bundle["sha256"])],
|
||||
files={key: len(value) for key, value in blobs.items()},
|
||||
)
|
||||
builds = ReplayBuilds(ReplayPublications(tmp_path / "worker"), tmp_path / "ffmpeg")
|
||||
app = FastAPI()
|
||||
app.include_router(build_replay_build_router(builds))
|
||||
return builds, TestClient(app), plan, blobs
|
||||
|
||||
|
||||
def test_transfer_is_verified_before_queue_and_identity_is_immutable(tmp_path):
|
||||
builds, client, plan, blobs = fixture(tmp_path)
|
||||
assert client.get(BUILD_PREFIX + "/" + RUN).status_code == 404
|
||||
assert client.post(BUILD_PREFIX, json=plan.model_dump()).status_code == 200
|
||||
prefix = BUILD_PREFIX + "/" + RUN
|
||||
assert client.post(prefix + "/commit").status_code == 409
|
||||
digest = next(iter(blobs))
|
||||
bad = b"x" * len(blobs[digest])
|
||||
assert client.put(prefix + "/inputs/" + digest, content=bad).status_code == 422
|
||||
assert not list(builds.root.glob("**/.upload-*"))
|
||||
for sha, value in blobs.items():
|
||||
assert client.put(prefix + "/inputs/" + sha, content=value).status_code == 200
|
||||
changed = plan.model_copy(update={"cache_key": "d" * 64})
|
||||
assert client.post(BUILD_PREFIX, json=changed.model_dump()).status_code == 409
|
||||
assert client.post(prefix + "/commit").json()["state"] == "queued"
|
||||
assert client.put(prefix + "/inputs/" + digest, content=blobs[digest]).status_code == 409
|
||||
|
||||
|
||||
def test_restart_finishes_publication_then_retires_only_owned_staging(tmp_path, monkeypatch):
|
||||
builds, client, plan, blobs = fixture(tmp_path)
|
||||
builds.register(plan)
|
||||
for sha, value in blobs.items():
|
||||
assert client.put(f"{BUILD_PREFIX}/{RUN}/inputs/{sha}", content=value).status_code == 200
|
||||
builds.commit(RUN)
|
||||
folder = builds.directory(RUN)
|
||||
_write(folder / "state.json", {"state": "building", "attempts": 1})
|
||||
crash_partial = folder / "inputs" / ".upload-abcdefgh"
|
||||
crash_partial.write_bytes(b"interrupted upload")
|
||||
protected = builds.root.parent / "protected.rrd"
|
||||
protected.write_bytes(b"existing working LAB")
|
||||
builds = ReplayBuilds(builds.publications, builds.ffmpeg)
|
||||
assert builds.status(RUN)["state"] == "queued"
|
||||
assert not crash_partial.exists()
|
||||
|
||||
def render(service, *args):
|
||||
service.cache.mkdir(parents=True)
|
||||
path = service.cache / "test.rrd"
|
||||
payload = b"RRF2complete"
|
||||
path.write_bytes(payload)
|
||||
return SimpleNamespace(
|
||||
path=path, byte_length=len(payload), sha256=hashlib.sha256(payload).hexdigest()
|
||||
)
|
||||
|
||||
monkeypatch.setattr(PortableReplayService, "prepare_composition", render)
|
||||
builds.run_once()
|
||||
assert builds.status(RUN)["state"] == "ready"
|
||||
manifest, recording = builds.publications.read(RUN, plan.base_sha256)
|
||||
assert recording.read_bytes() == b"RRF2complete"
|
||||
assert manifest.cache_key == plan.cache_key
|
||||
assert not (folder / "inputs").exists() and not (folder / "assembly").exists()
|
||||
assert protected.read_bytes() == b"existing working LAB"
|
||||
builds.run_once()
|
||||
assert builds.status(RUN)["attempts"] == 2
|
||||
assert builds.register(plan)["missing"] == []
|
||||
receipt = builds.publications.runtime / "state/data-ownership/receipts" / (RUN + ".json")
|
||||
_write(receipt, {"deleted": True})
|
||||
with pytest.raises(LabDeletionError):
|
||||
builds.register(plan)
|
||||
|
||||
|
||||
def test_assembly_failure_remains_retryable_without_model_execution(tmp_path, monkeypatch):
|
||||
builds, client, plan, blobs = fixture(tmp_path)
|
||||
builds.register(plan)
|
||||
for sha, value in blobs.items():
|
||||
client.put(f"{BUILD_PREFIX}/{RUN}/inputs/{sha}", content=value)
|
||||
builds.commit(RUN)
|
||||
monkeypatch.setattr(
|
||||
builds, "build", lambda _: (_ for _ in ()).throw(ValueError("codec failed"))
|
||||
)
|
||||
builds.run_once()
|
||||
assert builds.status(RUN)["state"] == "failed"
|
||||
assert not list(builds.publications.root.glob("**/manifest.json"))
|
||||
builds.run_once()
|
||||
assert builds.status(RUN)["attempts"] == 1
|
||||
assert builds.commit(RUN, retry=True)["state"] == "queued"
|
||||
assert len(list((builds.directory(RUN) / "inputs").iterdir())) == len(blobs)
|
||||
|
||||
|
||||
def test_new_run_never_falls_back_to_operator_assembly(tmp_path):
|
||||
builds, _, plan, _ = fixture(tmp_path)
|
||||
|
||||
def forbidden(_):
|
||||
pytest.fail("Operator source/render path must not execute")
|
||||
|
||||
service = PortableReplayService(
|
||||
view=SimpleNamespace(read=lambda _: plan.members[0].view),
|
||||
data_dir=tmp_path / "client",
|
||||
media=None,
|
||||
recording_source=forbidden,
|
||||
ffmpeg_path=tmp_path / "ffmpeg",
|
||||
worker_required=lambda _: True,
|
||||
remote_replays=SimpleNamespace(restore=lambda *args: None),
|
||||
)
|
||||
with pytest.raises(PortableReplayError, match="published by Worker"):
|
||||
service.prepare_composition(RUN, (RESULT,), plan.base_sha256)
|
||||
assert not service.cache.exists()
|
||||
Reference in New Issue
Block a user