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
+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)