feat(observatory): admit canonical recorded replay
This commit is contained in:
@@ -20,6 +20,7 @@ from .media import (
|
||||
validate_recorded_media_timeline,
|
||||
)
|
||||
from .models import (
|
||||
LabReplayCapability,
|
||||
LabSessionBinding,
|
||||
LayoutConflictError,
|
||||
ObservationArtifactCandidate,
|
||||
@@ -57,6 +58,7 @@ from .store import (
|
||||
|
||||
__all__ = [
|
||||
"LayoutConflictError",
|
||||
"LabReplayCapability",
|
||||
"LabSessionBinding",
|
||||
"ActiveSessionLease",
|
||||
"ActiveSessionLeaseError",
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Any, Literal
|
||||
|
||||
SessionStatus = Literal["ready", "interrupted", "failed"]
|
||||
SessionModality = Literal["point-cloud", "trajectory", "video"]
|
||||
LAB_REPLAY_CAPABILITY_SCHEMA = "missioncore.observation-lab-replay-capability/v1"
|
||||
|
||||
|
||||
class SessionStoreError(RuntimeError):
|
||||
@@ -28,6 +29,45 @@ class LayoutConflictError(SessionStoreError):
|
||||
"""A workspace layout revision changed since the caller loaded it."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class LabReplayCapability:
|
||||
"""Explicit, observation-only admission for a derived recorded replay."""
|
||||
|
||||
schema_version: Literal["missioncore.observation-lab-replay-capability/v1"]
|
||||
kind: Literal["canonical-recorded-rerun"]
|
||||
viewer_profile: Literal["recorded-session"]
|
||||
timeline: Literal["session_time"]
|
||||
activation: Literal["explicit"]
|
||||
commands_enabled: Literal[False]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
expected_text = (
|
||||
LAB_REPLAY_CAPABILITY_SCHEMA,
|
||||
"canonical-recorded-rerun",
|
||||
"recorded-session",
|
||||
"session_time",
|
||||
"explicit",
|
||||
)
|
||||
if (
|
||||
self.schema_version,
|
||||
self.kind,
|
||||
self.viewer_profile,
|
||||
self.timeline,
|
||||
self.activation,
|
||||
) != expected_text or self.commands_enabled is not False:
|
||||
raise ValueError("LAB replay capability is invalid")
|
||||
|
||||
def as_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"schema_version": self.schema_version,
|
||||
"kind": self.kind,
|
||||
"viewer_profile": self.viewer_profile,
|
||||
"timeline": self.timeline,
|
||||
"activation": self.activation,
|
||||
"commands_enabled": self.commands_enabled,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class LabSessionBinding:
|
||||
"""Immutable provenance for one derived laboratory replay."""
|
||||
@@ -41,10 +81,15 @@ class LabSessionBinding:
|
||||
config_sha256: str | None
|
||||
run_created_at_utc: str
|
||||
published_at_utc: str
|
||||
replay_capability: LabReplayCapability | None
|
||||
provenance: dict[str, Any]
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
def as_dict(
|
||||
self,
|
||||
*,
|
||||
include_replay_capability: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
document: dict[str, Any] = {
|
||||
"lab_id": self.lab_id,
|
||||
"source_session_id": self.source_session_id,
|
||||
"result_kind": self.result_kind,
|
||||
@@ -55,6 +100,11 @@ class LabSessionBinding:
|
||||
"published_at_utc": self.published_at_utc,
|
||||
"provenance": self.provenance,
|
||||
}
|
||||
if include_replay_capability:
|
||||
document["replay_capability"] = (
|
||||
None if self.replay_capability is None else self.replay_capability.as_dict()
|
||||
)
|
||||
return document
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -137,6 +187,8 @@ class SessionDetail:
|
||||
summary: SessionSummary
|
||||
sources: tuple[SessionSource, ...]
|
||||
artifacts: tuple[SessionArtifact, ...]
|
||||
plugin_id: str
|
||||
archive_id: str
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
duration = self.summary.duration_seconds
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
@@ -17,6 +18,7 @@ from uuid import uuid4
|
||||
from k1link.artifacts import utc_now_iso
|
||||
|
||||
from .models import (
|
||||
LabReplayCapability,
|
||||
LabSessionBinding,
|
||||
LayoutConflictError,
|
||||
ObservationArtifactCandidate,
|
||||
@@ -114,6 +116,8 @@ CREATE TABLE IF NOT EXISTS observation_lab_instances (
|
||||
config_sha256 TEXT,
|
||||
run_created_at_utc TEXT NOT NULL,
|
||||
published_at_utc TEXT NOT NULL,
|
||||
include_recorded_media INTEGER CHECK (include_recorded_media IN (0, 1)),
|
||||
replay_capability_json TEXT,
|
||||
provenance_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
@@ -213,10 +217,13 @@ class SessionStore:
|
||||
limit: int = 20,
|
||||
cursor: str | None = None,
|
||||
scope: SessionScope = "all",
|
||||
include_capability_projections: bool = True,
|
||||
) -> SessionPage:
|
||||
if not 1 <= limit <= 100:
|
||||
raise ValueError("limit must be within 1..100")
|
||||
scope_clause = {
|
||||
if not isinstance(include_capability_projections, bool):
|
||||
raise ValueError("capability projection policy must be boolean")
|
||||
scope_clause = ({
|
||||
"all": "1 = 1",
|
||||
"source": (
|
||||
"NOT EXISTS (SELECT 1 FROM observation_lab_instances AS lab "
|
||||
@@ -226,7 +233,22 @@ class SessionStore:
|
||||
"EXISTS (SELECT 1 FROM observation_lab_instances AS lab "
|
||||
"WHERE lab.session_id = sessions.session_id)"
|
||||
),
|
||||
}.get(scope)
|
||||
} if include_capability_projections else {
|
||||
"all": (
|
||||
"NOT EXISTS (SELECT 1 FROM observation_lab_instances AS lab "
|
||||
"WHERE lab.session_id = sessions.session_id "
|
||||
"AND lab.replay_capability_json IS NOT NULL)"
|
||||
),
|
||||
"source": (
|
||||
"NOT EXISTS (SELECT 1 FROM observation_lab_instances AS lab "
|
||||
"WHERE lab.session_id = sessions.session_id)"
|
||||
),
|
||||
"laboratory": (
|
||||
"EXISTS (SELECT 1 FROM observation_lab_instances AS lab "
|
||||
"WHERE lab.session_id = sessions.session_id "
|
||||
"AND lab.replay_capability_json IS NULL)"
|
||||
),
|
||||
}).get(scope)
|
||||
if scope_clause is None:
|
||||
raise ValueError("scope must be all, source, or laboratory")
|
||||
parameters: list[object] = []
|
||||
@@ -283,8 +305,18 @@ class SessionStore:
|
||||
return SessionPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
def get_session(self, session_id: str) -> SessionDetail:
|
||||
detail, _snapshot_sha256 = self.get_session_with_catalog_snapshot(session_id)
|
||||
return detail
|
||||
|
||||
def get_session_with_catalog_snapshot(
|
||||
self,
|
||||
session_id: str,
|
||||
) -> tuple[SessionDetail, str]:
|
||||
"""Read one detail and its private catalog snapshot from one SQLite view."""
|
||||
|
||||
_validate_identifier(session_id, "session id")
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN")
|
||||
row = connection.execute(
|
||||
"SELECT * FROM observation_sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
@@ -292,19 +324,20 @@ class SessionStore:
|
||||
if row is None:
|
||||
raise SessionNotFoundError("observation session was not found")
|
||||
source_rows = connection.execute(
|
||||
"SELECT source_id, semantic_channel_id, modality, status, seekable, artifact_id "
|
||||
"FROM observation_session_sources WHERE session_id = ? ORDER BY source_id",
|
||||
"SELECT * FROM observation_session_sources "
|
||||
"WHERE session_id = ? ORDER BY source_id",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
artifact_rows = connection.execute(
|
||||
"SELECT artifact_id, kind, media_type, byte_length, sha256, integrity_status "
|
||||
"FROM observation_session_artifacts WHERE session_id = ? ORDER BY artifact_id",
|
||||
"SELECT * FROM observation_session_artifacts "
|
||||
"WHERE session_id = ? ORDER BY artifact_id",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
lab_row = connection.execute(
|
||||
"SELECT * FROM observation_lab_instances WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
snapshot_sha256 = _catalog_snapshot_sha256(row, source_rows, artifact_rows)
|
||||
sources = tuple(
|
||||
SessionSource(
|
||||
source_id=source["source_id"],
|
||||
@@ -327,14 +360,17 @@ class SessionStore:
|
||||
)
|
||||
for artifact in artifact_rows
|
||||
)
|
||||
return SessionDetail(
|
||||
detail = SessionDetail(
|
||||
summary=_summary_from_row(
|
||||
row,
|
||||
lab=None if lab_row is None else _lab_binding_from_row(lab_row),
|
||||
),
|
||||
sources=sources,
|
||||
artifacts=artifacts,
|
||||
plugin_id=row["plugin_id"],
|
||||
archive_id=row["archive_id"],
|
||||
)
|
||||
return detail, snapshot_sha256
|
||||
|
||||
def get_lab_instance(self, session_id: str) -> LabSessionBinding | None:
|
||||
"""Return immutable LAB provenance without exposing filesystem locators."""
|
||||
@@ -359,9 +395,11 @@ class SessionStore:
|
||||
run_created_at_utc: str,
|
||||
source_result_id: str | None = None,
|
||||
config_sha256: str | None = None,
|
||||
replay_capability: LabReplayCapability | None = None,
|
||||
provenance: dict[str, Any] | None = None,
|
||||
duration_seconds: float | None = None,
|
||||
include_recorded_media: bool = True,
|
||||
expected_source_catalog_sha256: str | None = None,
|
||||
) -> LabSessionBinding:
|
||||
"""Append one immutable catalog projection over an existing source session.
|
||||
|
||||
@@ -392,9 +430,22 @@ class SessionStore:
|
||||
or duration_seconds <= 0
|
||||
):
|
||||
raise ValueError("LAB duration must be a positive finite value")
|
||||
if not isinstance(include_recorded_media, bool):
|
||||
raise ValueError("LAB recorded-media policy must be boolean")
|
||||
if (
|
||||
expected_source_catalog_sha256 is not None
|
||||
and SHA256_PATTERN.fullmatch(expected_source_catalog_sha256) is None
|
||||
):
|
||||
raise ValueError("LAB source catalog snapshot SHA-256 is invalid")
|
||||
normalized_provenance = provenance or {}
|
||||
_validate_lab_method(normalized_provenance)
|
||||
_validate_replay_capability_provenance(
|
||||
normalized_provenance,
|
||||
replay_capability,
|
||||
)
|
||||
serialized_provenance = _serialize_provenance(normalized_provenance)
|
||||
serialized_replay_capability = _serialize_replay_capability(replay_capability)
|
||||
serialized_recorded_media_policy = int(include_recorded_media)
|
||||
published_at = utc_now_iso()
|
||||
|
||||
with self._lock, self._connect() as connection:
|
||||
@@ -406,6 +457,19 @@ class SessionStore:
|
||||
if source is None:
|
||||
connection.rollback()
|
||||
raise SessionNotFoundError("LAB source observation session was not found")
|
||||
if (
|
||||
expected_source_catalog_sha256 is not None
|
||||
and _catalog_snapshot_sha256_for_session(
|
||||
connection,
|
||||
source_session_id,
|
||||
session_row=source,
|
||||
)
|
||||
!= expected_source_catalog_sha256
|
||||
):
|
||||
connection.rollback()
|
||||
raise SessionIntegrityError(
|
||||
"LAB source catalog changed after admission"
|
||||
)
|
||||
if (
|
||||
connection.execute(
|
||||
"SELECT 1 FROM observation_lab_instances WHERE session_id = ?",
|
||||
@@ -428,6 +492,7 @@ class SessionStore:
|
||||
"source_result_id": source_result_id,
|
||||
"config_sha256": config_sha256,
|
||||
"run_created_at_utc": run_created_at_utc,
|
||||
"replay_capability_json": serialized_replay_capability,
|
||||
"provenance_json": serialized_provenance,
|
||||
}
|
||||
if existing is not None:
|
||||
@@ -436,6 +501,36 @@ class SessionStore:
|
||||
raise SessionIntegrityError(
|
||||
"LAB session id is already bound to different provenance"
|
||||
)
|
||||
if replay_capability is not None:
|
||||
stored_recorded_media_policy = existing["include_recorded_media"]
|
||||
if (
|
||||
stored_recorded_media_policy is not None
|
||||
and stored_recorded_media_policy != serialized_recorded_media_policy
|
||||
):
|
||||
connection.rollback()
|
||||
raise SessionIntegrityError(
|
||||
"LAB session id is already bound to a different recorded-media policy"
|
||||
)
|
||||
_validate_existing_lab_projection(
|
||||
connection,
|
||||
session_id=session_id,
|
||||
source_session_id=source_session_id,
|
||||
display_name=normalized_name,
|
||||
run_created_at_utc=run_created_at_utc,
|
||||
duration_seconds=(
|
||||
source["duration_seconds"]
|
||||
if duration_seconds is None
|
||||
else duration_seconds
|
||||
),
|
||||
include_recorded_media=include_recorded_media,
|
||||
)
|
||||
if stored_recorded_media_policy is None:
|
||||
connection.execute(
|
||||
"UPDATE observation_lab_instances SET include_recorded_media = ? "
|
||||
"WHERE session_id = ?",
|
||||
(serialized_recorded_media_policy, session_id),
|
||||
)
|
||||
_synchronize_lab_projection_summary(connection, session_id)
|
||||
connection.commit()
|
||||
return _lab_binding_from_row(existing)
|
||||
if (
|
||||
@@ -507,8 +602,8 @@ class SessionStore:
|
||||
"INSERT INTO observation_lab_instances "
|
||||
"(session_id, source_session_id, lab_id, result_kind, result_id, "
|
||||
"source_result_id, config_sha256, run_created_at_utc, "
|
||||
"published_at_utc, provenance_json) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
"published_at_utc, include_recorded_media, replay_capability_json, "
|
||||
"provenance_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
session_id,
|
||||
source_session_id,
|
||||
@@ -519,9 +614,13 @@ class SessionStore:
|
||||
config_sha256,
|
||||
run_created_at_utc,
|
||||
published_at,
|
||||
serialized_recorded_media_policy,
|
||||
serialized_replay_capability,
|
||||
serialized_provenance,
|
||||
),
|
||||
)
|
||||
if replay_capability is not None:
|
||||
_synchronize_lab_projection_summary(connection, session_id)
|
||||
connection.commit()
|
||||
binding = self.get_lab_instance(session_id)
|
||||
if binding is None:
|
||||
@@ -817,6 +916,22 @@ class SessionStore:
|
||||
"ALTER TABLE observation_session_artifacts "
|
||||
"ADD COLUMN replay_byte_length INTEGER NOT NULL DEFAULT 0"
|
||||
)
|
||||
lab_columns = {
|
||||
row["name"]
|
||||
for row in connection.execute("PRAGMA table_info(observation_lab_instances)")
|
||||
}
|
||||
if "replay_capability_json" not in lab_columns:
|
||||
connection.execute(
|
||||
"ALTER TABLE observation_lab_instances "
|
||||
"ADD COLUMN replay_capability_json TEXT"
|
||||
)
|
||||
if "include_recorded_media" not in lab_columns:
|
||||
connection.execute(
|
||||
"ALTER TABLE observation_lab_instances "
|
||||
"ADD COLUMN include_recorded_media INTEGER "
|
||||
"CHECK (include_recorded_media IN (0, 1))"
|
||||
)
|
||||
_migrate_canonical_replay_capabilities(connection)
|
||||
connection.commit()
|
||||
with _ignore_os_error():
|
||||
self.database_path.chmod(0o600)
|
||||
@@ -1046,6 +1161,428 @@ def _validate_candidate_replay(
|
||||
raise SessionIntegrityError("non-replayable observation declares replay artifacts")
|
||||
|
||||
|
||||
def _validate_existing_lab_projection(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
session_id: str,
|
||||
source_session_id: str,
|
||||
display_name: str,
|
||||
run_created_at_utc: str,
|
||||
duration_seconds: float | None,
|
||||
include_recorded_media: bool,
|
||||
) -> None:
|
||||
"""Validate the immutable companion snapshot without rereading a mutable source row."""
|
||||
|
||||
summary = connection.execute(
|
||||
"SELECT * FROM observation_sessions "
|
||||
"WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
source_summary = connection.execute(
|
||||
"SELECT * FROM observation_sessions WHERE session_id = ?",
|
||||
(source_session_id,),
|
||||
).fetchone()
|
||||
if (
|
||||
summary is None
|
||||
or source_summary is None
|
||||
or summary["display_name"] != display_name
|
||||
or summary["duration_seconds"] != duration_seconds
|
||||
or summary["plugin_id"] != source_summary["plugin_id"]
|
||||
or summary["archive_id"] != LAB_ARCHIVE_ID
|
||||
or summary["status"] != source_summary["status"]
|
||||
or summary["started_at_utc"] != run_created_at_utc
|
||||
or summary["completed_at_utc"] != run_created_at_utc
|
||||
or summary["replayable"] != source_summary["replayable"]
|
||||
or summary["origin"] != LAB_ORIGIN
|
||||
or summary["primary_replay_artifact_id"]
|
||||
!= source_summary["primary_replay_artifact_id"]
|
||||
or summary["timeline_origin_epoch_ns"]
|
||||
!= source_summary["timeline_origin_epoch_ns"]
|
||||
or summary["timeline_origin_monotonic_ns"]
|
||||
!= source_summary["timeline_origin_monotonic_ns"]
|
||||
or summary["allowed_root"] != source_summary["allowed_root"]
|
||||
or summary["session_root"] != source_summary["session_root"]
|
||||
):
|
||||
raise SessionIntegrityError(
|
||||
"LAB session id is already bound to different catalog metadata"
|
||||
)
|
||||
if (
|
||||
summary["status"] != "ready"
|
||||
or summary["replayable"] != 1
|
||||
or summary["primary_replay_artifact_id"] is None
|
||||
or summary["timeline_origin_epoch_ns"] is None
|
||||
or summary["timeline_origin_monotonic_ns"] is None
|
||||
or summary["timeline_origin_epoch_ns"] < 0
|
||||
or summary["timeline_origin_monotonic_ns"] < 0
|
||||
):
|
||||
raise SessionIntegrityError(
|
||||
"LAB replay projection is not a complete ready recording"
|
||||
)
|
||||
if not include_recorded_media and (
|
||||
connection.execute(
|
||||
"SELECT 1 FROM observation_session_sources "
|
||||
"WHERE session_id = ? AND modality = 'video' LIMIT 1",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
is not None
|
||||
or connection.execute(
|
||||
"SELECT 1 FROM observation_session_artifacts "
|
||||
"WHERE session_id = ? AND kind = 'recorded-video' LIMIT 1",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
is not None
|
||||
):
|
||||
raise SessionIntegrityError(
|
||||
"LAB session id is already bound to a different recorded-media policy"
|
||||
)
|
||||
_validate_lab_projection_rows_match_source(
|
||||
connection,
|
||||
session_id=session_id,
|
||||
source_session_id=source_session_id,
|
||||
include_recorded_media=include_recorded_media,
|
||||
)
|
||||
|
||||
|
||||
def _validate_lab_projection_rows_match_source(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
session_id: str,
|
||||
source_session_id: str,
|
||||
include_recorded_media: bool,
|
||||
) -> None:
|
||||
source_filter = "" if include_recorded_media else " AND modality <> 'video'"
|
||||
artifact_filter = "" if include_recorded_media else " AND kind <> 'recorded-video'"
|
||||
source_columns = (
|
||||
"source_id",
|
||||
"semantic_channel_id",
|
||||
"modality",
|
||||
"status",
|
||||
"seekable",
|
||||
"artifact_id",
|
||||
)
|
||||
artifact_columns = (
|
||||
"artifact_id",
|
||||
"kind",
|
||||
"media_type",
|
||||
"byte_length",
|
||||
"sha256",
|
||||
"integrity_status",
|
||||
"locator",
|
||||
"replay_byte_length",
|
||||
)
|
||||
expected_sources = connection.execute(
|
||||
"SELECT * FROM observation_session_sources WHERE session_id = ?"
|
||||
f"{source_filter} ORDER BY source_id", # noqa: S608 - closed static fragment
|
||||
(source_session_id,),
|
||||
).fetchall()
|
||||
actual_sources = connection.execute(
|
||||
"SELECT * FROM observation_session_sources "
|
||||
"WHERE session_id = ? ORDER BY source_id",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
expected_artifacts = connection.execute(
|
||||
"SELECT * FROM observation_session_artifacts WHERE session_id = ?"
|
||||
f"{artifact_filter} ORDER BY artifact_id", # noqa: S608 - closed static fragment
|
||||
(source_session_id,),
|
||||
).fetchall()
|
||||
actual_artifacts = connection.execute(
|
||||
"SELECT * FROM observation_session_artifacts "
|
||||
"WHERE session_id = ? ORDER BY artifact_id",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
|
||||
def values(
|
||||
rows: list[sqlite3.Row],
|
||||
columns: tuple[str, ...],
|
||||
) -> tuple[tuple[object, ...], ...]:
|
||||
return tuple(tuple(row[column] for column in columns) for row in rows)
|
||||
|
||||
if (
|
||||
values(actual_sources, source_columns)
|
||||
!= values(expected_sources, source_columns)
|
||||
or values(actual_artifacts, artifact_columns)
|
||||
!= values(expected_artifacts, artifact_columns)
|
||||
):
|
||||
raise SessionIntegrityError(
|
||||
"LAB replay projection no longer matches its admitted source snapshot"
|
||||
)
|
||||
|
||||
|
||||
def _synchronize_lab_projection_summary(
|
||||
connection: sqlite3.Connection,
|
||||
session_id: str,
|
||||
) -> None:
|
||||
"""Make the synthetic summary describe exactly its copied rows."""
|
||||
|
||||
summary = connection.execute(
|
||||
"SELECT modalities_json, source_count, total_bytes, replayable, "
|
||||
"primary_replay_artifact_id "
|
||||
"FROM observation_sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
if summary is None:
|
||||
raise SessionIntegrityError("LAB projection catalog row is missing")
|
||||
try:
|
||||
declared_modalities = json.loads(summary["modalities_json"])
|
||||
except (TypeError, json.JSONDecodeError) as exc:
|
||||
raise SessionIntegrityError("LAB projection modalities are invalid") from exc
|
||||
if not isinstance(declared_modalities, list) or not all(
|
||||
isinstance(value, str) for value in declared_modalities
|
||||
):
|
||||
raise SessionIntegrityError("LAB projection modalities are invalid")
|
||||
|
||||
actual_modalities = {
|
||||
row["modality"]
|
||||
for row in connection.execute(
|
||||
"SELECT DISTINCT modality FROM observation_session_sources "
|
||||
"WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
}
|
||||
modalities: list[str] = []
|
||||
for value in declared_modalities:
|
||||
if value in actual_modalities and value not in modalities:
|
||||
modalities.append(value)
|
||||
modalities.extend(sorted(actual_modalities.difference(modalities)))
|
||||
source_count = connection.execute(
|
||||
"SELECT COUNT(*) AS value FROM observation_session_sources WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()["value"]
|
||||
total_bytes = connection.execute(
|
||||
"SELECT COALESCE(SUM(byte_length), 0) AS value "
|
||||
"FROM observation_session_artifacts WHERE session_id = ? "
|
||||
"AND artifact_id IN ("
|
||||
"SELECT DISTINCT artifact_id FROM observation_session_sources "
|
||||
"WHERE session_id = ?)",
|
||||
(session_id, session_id),
|
||||
).fetchone()["value"]
|
||||
primary_artifact_id = summary["primary_replay_artifact_id"]
|
||||
if summary["replayable"] and (
|
||||
primary_artifact_id is None
|
||||
or connection.execute(
|
||||
"SELECT 1 FROM observation_session_artifacts "
|
||||
"WHERE session_id = ? AND artifact_id = ?",
|
||||
(session_id, primary_artifact_id),
|
||||
).fetchone()
|
||||
is None
|
||||
):
|
||||
raise SessionIntegrityError(
|
||||
"LAB projection omitted its primary replay artifact"
|
||||
)
|
||||
modalities_json = json.dumps(modalities, separators=(",", ":"))
|
||||
if (
|
||||
summary["modalities_json"] != modalities_json
|
||||
or summary["source_count"] != source_count
|
||||
or summary["total_bytes"] != total_bytes
|
||||
):
|
||||
connection.execute(
|
||||
"UPDATE observation_sessions SET modalities_json = ?, source_count = ?, "
|
||||
"total_bytes = ?, updated_at_utc = ? WHERE session_id = ?",
|
||||
(
|
||||
modalities_json,
|
||||
source_count,
|
||||
total_bytes,
|
||||
utc_now_iso(),
|
||||
session_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _catalog_snapshot_sha256_for_session(
|
||||
connection: sqlite3.Connection,
|
||||
session_id: str,
|
||||
*,
|
||||
session_row: sqlite3.Row | None = None,
|
||||
) -> str:
|
||||
row = (
|
||||
session_row
|
||||
if session_row is not None
|
||||
else connection.execute(
|
||||
"SELECT * FROM observation_sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
)
|
||||
if row is None:
|
||||
raise SessionNotFoundError("observation session was not found")
|
||||
source_rows = connection.execute(
|
||||
"SELECT * FROM observation_session_sources "
|
||||
"WHERE session_id = ? ORDER BY source_id",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
artifact_rows = connection.execute(
|
||||
"SELECT * FROM observation_session_artifacts "
|
||||
"WHERE session_id = ? ORDER BY artifact_id",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
return _catalog_snapshot_sha256(row, source_rows, artifact_rows)
|
||||
|
||||
|
||||
def _catalog_snapshot_sha256(
|
||||
session_row: sqlite3.Row,
|
||||
source_rows: list[sqlite3.Row],
|
||||
artifact_rows: list[sqlite3.Row],
|
||||
) -> str:
|
||||
"""Bind every stored field copied or referenced by a LAB projection."""
|
||||
|
||||
payload = {
|
||||
"session": dict(session_row),
|
||||
"sources": [dict(row) for row in source_rows],
|
||||
"artifacts": [dict(row) for row in artifact_rows],
|
||||
}
|
||||
serialized = json.dumps(
|
||||
payload,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
return hashlib.sha256(serialized).hexdigest()
|
||||
|
||||
|
||||
def _migrate_canonical_replay_capabilities(connection: sqlite3.Connection) -> None:
|
||||
"""Type the one rolling-upgrade projection that predates the v2 column."""
|
||||
|
||||
rows = connection.execute(
|
||||
"SELECT * FROM observation_lab_instances "
|
||||
"WHERE replay_capability_json IS NULL OR include_recorded_media IS NULL"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
try:
|
||||
provenance = json.loads(row["provenance_json"])
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
continue
|
||||
capability = _canonical_rolling_capability(row, provenance)
|
||||
if capability is None:
|
||||
continue
|
||||
serialized = _serialize_replay_capability(capability)
|
||||
stored = row["replay_capability_json"]
|
||||
if stored is not None and stored != serialized:
|
||||
raise SessionIntegrityError(
|
||||
"stored canonical LAB replay capability conflicts with provenance"
|
||||
)
|
||||
summary = connection.execute(
|
||||
"SELECT * FROM observation_sessions WHERE session_id = ?",
|
||||
(row["session_id"],),
|
||||
).fetchone()
|
||||
if summary is None:
|
||||
raise SessionIntegrityError("canonical LAB catalog row is missing")
|
||||
source_summary = connection.execute(
|
||||
"SELECT * FROM observation_sessions WHERE session_id = ?",
|
||||
(row["source_session_id"],),
|
||||
).fetchone()
|
||||
if (
|
||||
summary["display_name"]
|
||||
!= "RAVNOVES004TREE · полный маршрут восприятия"
|
||||
or summary["duration_seconds"] != 718.0
|
||||
or row["run_created_at_utc"]
|
||||
!= "2026-08-29T18:05:11.329061+00:00"
|
||||
or source_summary is None
|
||||
or source_summary["plugin_id"]
|
||||
!= "nodedc.device.xgrids-lixelkity-k1"
|
||||
or source_summary["archive_id"] != "xgrids-k1.viewer-live.evidence"
|
||||
):
|
||||
raise SessionIntegrityError(
|
||||
"canonical rolling LAB projection metadata is invalid"
|
||||
)
|
||||
_validate_existing_lab_projection(
|
||||
connection,
|
||||
session_id=row["session_id"],
|
||||
source_session_id=row["source_session_id"],
|
||||
display_name=summary["display_name"],
|
||||
run_created_at_utc=row["run_created_at_utc"],
|
||||
duration_seconds=summary["duration_seconds"],
|
||||
include_recorded_media=False,
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE observation_lab_instances SET replay_capability_json = ?, "
|
||||
"include_recorded_media = 0 WHERE session_id = ?",
|
||||
(serialized, row["session_id"]),
|
||||
)
|
||||
_synchronize_lab_projection_summary(connection, row["session_id"])
|
||||
|
||||
|
||||
def _canonical_rolling_capability(
|
||||
row: sqlite3.Row,
|
||||
provenance: object,
|
||||
) -> LabReplayCapability | None:
|
||||
if not isinstance(provenance, dict) or set(provenance) != {
|
||||
"schema_version",
|
||||
"evidence_identity_sha256",
|
||||
"result_document_sha256",
|
||||
"replay_capability",
|
||||
"authority",
|
||||
"method",
|
||||
}:
|
||||
return None
|
||||
evidence_identity = provenance.get("evidence_identity_sha256")
|
||||
result_document = provenance.get("result_document_sha256")
|
||||
expected_result_id = (
|
||||
f"lab-v1-vegetation-shadow-{evidence_identity}"
|
||||
if isinstance(evidence_identity, str)
|
||||
else None
|
||||
)
|
||||
if (
|
||||
provenance.get("schema_version")
|
||||
!= "missioncore.canonical-recorded-lab-projection/v1"
|
||||
or not isinstance(evidence_identity, str)
|
||||
or SHA256_PATTERN.fullmatch(evidence_identity) is None
|
||||
or not isinstance(result_document, str)
|
||||
or SHA256_PATTERN.fullmatch(result_document) is None
|
||||
or row["session_id"] != expected_result_id
|
||||
or row["result_id"] != expected_result_id
|
||||
or row["source_session_id"] != "20260828T130511Z_viewer_live"
|
||||
or row["lab_id"] != "LAB V1"
|
||||
or row["result_kind"] != "recorded-perception-qualification"
|
||||
or row["config_sha256"] is not None
|
||||
or not isinstance(row["source_result_id"], str)
|
||||
or re.fullmatch(
|
||||
r"lab-v1-vegetation-shadow-[a-f0-9]{64}",
|
||||
row["source_result_id"],
|
||||
)
|
||||
is None
|
||||
):
|
||||
return None
|
||||
authority = provenance.get("authority")
|
||||
authority_keys = {
|
||||
"commands_enabled",
|
||||
"navigation_or_safety_accepted",
|
||||
"actuation_accepted",
|
||||
}
|
||||
if (
|
||||
not isinstance(authority, dict)
|
||||
or set(authority) != authority_keys
|
||||
or any(authority[key] is not False for key in authority_keys)
|
||||
):
|
||||
return None
|
||||
method = provenance.get("method")
|
||||
expected_component = {
|
||||
"kind": "source",
|
||||
"name": "sealed full-route LAB result",
|
||||
"version": "missioncore.lab-v1-vegetation-shadow/v1",
|
||||
"role": "immutable Session catalog projection",
|
||||
"identity_sha256": evidence_identity,
|
||||
}
|
||||
if method != {
|
||||
"schema_version": LAB_METHOD_SCHEMA,
|
||||
"completeness": "legacy-partial",
|
||||
"execution_class": "ai-inference",
|
||||
"pipeline_id": "ravnoves004tree-full-eomt-ddrnet-recorded-review/v1",
|
||||
"components": [expected_component],
|
||||
}:
|
||||
return None
|
||||
capability_document = provenance.get("replay_capability")
|
||||
try:
|
||||
serialized = json.dumps(
|
||||
capability_document,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
)
|
||||
return _replay_capability_from_row(serialized)
|
||||
except (TypeError, ValueError, SessionIntegrityError):
|
||||
return None
|
||||
|
||||
|
||||
def _summary_from_row(
|
||||
row: sqlite3.Row,
|
||||
*,
|
||||
@@ -1076,6 +1613,13 @@ def _lab_binding_from_row(row: sqlite3.Row) -> LabSessionBinding:
|
||||
raise SessionIntegrityError("stored LAB provenance is invalid") from exc
|
||||
if not isinstance(provenance, dict):
|
||||
raise SessionIntegrityError("stored LAB provenance is not an object")
|
||||
replay_capability = _replay_capability_from_row(row["replay_capability_json"])
|
||||
try:
|
||||
_validate_replay_capability_provenance(provenance, replay_capability)
|
||||
except ValueError as exc:
|
||||
raise SessionIntegrityError(
|
||||
"stored LAB replay capability does not match provenance"
|
||||
) from exc
|
||||
return LabSessionBinding(
|
||||
session_id=row["session_id"],
|
||||
source_session_id=row["source_session_id"],
|
||||
@@ -1086,10 +1630,66 @@ def _lab_binding_from_row(row: sqlite3.Row) -> LabSessionBinding:
|
||||
config_sha256=row["config_sha256"],
|
||||
run_created_at_utc=row["run_created_at_utc"],
|
||||
published_at_utc=row["published_at_utc"],
|
||||
replay_capability=replay_capability,
|
||||
provenance=provenance,
|
||||
)
|
||||
|
||||
|
||||
def _serialize_replay_capability(value: LabReplayCapability | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, LabReplayCapability):
|
||||
raise ValueError("LAB replay capability must use the typed contract")
|
||||
return json.dumps(value.as_dict(), sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def _replay_capability_from_row(value: object) -> LabReplayCapability | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
document = json.loads(value)
|
||||
except (TypeError, json.JSONDecodeError) as exc:
|
||||
raise SessionIntegrityError("stored LAB replay capability is invalid") from exc
|
||||
expected_keys = {
|
||||
"schema_version",
|
||||
"kind",
|
||||
"viewer_profile",
|
||||
"timeline",
|
||||
"activation",
|
||||
"commands_enabled",
|
||||
}
|
||||
if not isinstance(document, dict) or set(document) != expected_keys:
|
||||
raise SessionIntegrityError("stored LAB replay capability is invalid")
|
||||
try:
|
||||
return LabReplayCapability(
|
||||
schema_version=document["schema_version"],
|
||||
kind=document["kind"],
|
||||
viewer_profile=document["viewer_profile"],
|
||||
timeline=document["timeline"],
|
||||
activation=document["activation"],
|
||||
commands_enabled=document["commands_enabled"],
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise SessionIntegrityError("stored LAB replay capability is invalid") from exc
|
||||
|
||||
|
||||
def _validate_replay_capability_provenance(
|
||||
provenance: dict[str, Any],
|
||||
capability: LabReplayCapability | None,
|
||||
) -> None:
|
||||
declared = provenance.get("replay_capability")
|
||||
if capability is None:
|
||||
if declared is not None:
|
||||
raise ValueError("LAB provenance cannot grant an untyped replay capability")
|
||||
return
|
||||
if (
|
||||
not isinstance(declared, dict)
|
||||
or _serialize_provenance(declared)
|
||||
!= _serialize_provenance(capability.as_dict())
|
||||
):
|
||||
raise ValueError("LAB replay capability must exactly match provenance")
|
||||
|
||||
|
||||
def _serialize_provenance(value: dict[str, Any]) -> str:
|
||||
try:
|
||||
serialized = json.dumps(
|
||||
|
||||
Reference in New Issue
Block a user