Assemble complete modular LAB recordings on Worker before readiness

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 04:44:02 +03:00
parent 800518ea80
commit 58ac9fe3d2
12 changed files with 989 additions and 49 deletions
@@ -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")
+358
View File
@@ -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
+26 -4
View File
@@ -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
+8 -1
View File
@@ -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")),
)
+37 -23
View File
@@ -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)
+35 -17
View File
@@ -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(
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,
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,
)
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,
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
),
)
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:
+25 -2
View File
@@ -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(