From fe5900ff3b0906c2298f0a09e63e90ca2880f86d Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Tue, 10 Nov 2026 01:09:39 +0300 Subject: [PATCH] refactor(lab): move execution to Worker and manage replay and transfer lifecycles --- AGENTS.md | 60 ++ .../components/EnvironmentSettingsWindow.tsx | 4 +- .../laboratory/CanonicalResultRerunReplay.tsx | 23 +- .../laboratory/LabReplayProgress.tsx | 10 + .../observatory/FailedRunActions.tsx | 29 + .../components/observatory/LabCopyActions.tsx | 71 ++ .../components/storage/LabStorageSettings.tsx | 32 + .../src/core/laboratory/prepareLabReplay.ts | 57 + .../src/core/observatory/catalog.ts | 11 +- .../src/core/observatory/catalogMutations.ts | 16 +- .../src/core/observatory/failedRunHistory.ts | 24 + .../useObservatoryLaboratorySetups.ts | 132 --- .../observatory/useObservatoryRecordedJobs.ts | 207 ---- .../src/core/storage/localLabPresentation.ts | 11 + .../src/core/storage/localLabStorage.ts | 73 ++ .../src/styles/m4-replay-threat.css | 21 + .../observatory/ObservatoryWorkspace.tsx | 86 +- .../test/failedRunHistory.test.mjs | 21 + .../test/labReplayPreparation.test.mjs | 55 + .../test/observatoryCatalog.test.mjs | 17 +- .../test/observatoryCatalogMutations.test.mjs | 11 + .../test/observatoryHooks.test.mjs | 96 -- .../test/observatoryWorkspace.test.mjs | 18 +- .../observatory-portable-run-definitions.json | 571 +++++++++- ...observatory-worker-runtime-candidates.json | 685 +++++++++++- deploy/laboratory/Dockerfile | 19 + deploy/laboratory/README.md | 160 +++ deploy/laboratory/compose.yaml | 60 ++ deploy/laboratory/install_operator_link.py | 74 ++ deploy/laboratory/requirements.lock | 452 ++++++++ deploy/laboratory/retire_fixed_lab_v1.ps1 | 52 + deploy/laboratory/verify_runtime.py | 63 ++ docs/LAB_AND_INSTALLER_STORAGE.md | 343 ++++++ docs/STORAGE_RETENTION.md | 220 ++++ .../promote_installed_lab_v1_package.py | 116 +- scripts/build_modular_ai_worker_release.py | 35 +- src/k1link/cache_budget.py | 17 +- src/k1link/compute/integrated_perception.py | 8 +- src/k1link/laboratory/archive_store.py | 192 ++++ src/k1link/laboratory/data_deletion.py | 181 ++++ src/k1link/laboratory/deletion_coordinator.py | 110 ++ src/k1link/laboratory/deletion_inventory.py | 197 ++++ src/k1link/laboratory/execution.py | 26 +- src/k1link/laboratory/execution_authority.py | 47 + src/k1link/laboratory/local_presentations.py | 222 ++++ src/k1link/laboratory/materialize_archive.py | 114 ++ .../materialize_recorded_sources.py | 144 +++ src/k1link/laboratory/worker_gateway.py | 224 ++++ .../laboratory/worker_recorded_sources.py | 89 ++ src/k1link/laboratory/worker_server.py | 167 +++ .../observatory/modular_model_assets.py | 111 ++ .../portable_artifact_transport.py | 717 ++++++------- src/k1link/observatory/portable_replay.py | 22 +- .../observatory/portable_result_cache.py | 4 + .../observatory/portable_result_publisher.py | 332 +++++- .../observatory/portable_result_view.py | 8 +- src/k1link/observatory/recorded_jobs.py | 59 +- .../observatory/source_transport_lifecycle.py | 221 ++++ src/k1link/observatory/transfer_space.py | 170 +++ src/k1link/sessions/camera_frame.py | 30 +- src/k1link/sessions/store.py | 25 +- src/k1link/web/app.py | 994 ++---------------- src/k1link/web/local_storage_api.py | 49 + src/k1link/web/modular_observatory_api.py | 39 +- src/k1link/web/observatory_api.py | 10 +- src/k1link/web/observatory_worker_api.py | 153 +-- src/k1link/web/portable_replay_api.py | 83 +- src/k1link/web/session_api.py | 46 +- src/k1link/web/source_transfer_response.py | 21 + .../web/worker_laboratory_presentation.py | 129 +++ src/k1link/web/worker_laboratory_surface.py | 890 ++++++++++++++++ .../observatory/retired-fixed-lab/README.md | 3 + .../observatory-portable-run-definitions.json | 1 + ...observatory-worker-runtime-candidates.json | 1 + tests/test_camera_frame.py | 33 +- tests/test_fixed_lab_retirement.py | 80 ++ tests/test_lab_data_deletion.py | 183 ++++ tests/test_laboratory_archive_store.py | 156 +++ tests/test_laboratory_execution.py | 27 +- tests/test_laboratory_worker_gateway.py | 139 +++ tests/test_laboratory_worker_sources.py | 50 + tests/test_local_presentations.py | 117 +++ tests/test_modular_observatory_api.py | 6 +- ...bservatory_installed_lab_package_runner.py | 12 +- ...test_observatory_installed_lab_packages.py | 12 +- ..._observatory_installed_lab_v1_promotion.py | 30 +- .../test_observatory_m49_worker_entrypoint.py | 6 +- ...observatory_portable_artifact_transport.py | 213 +++- ...t_observatory_portable_lab_v1_promotion.py | 39 +- ...ervatory_portable_lab_v1_worker_service.py | 67 +- ...test_observatory_portable_queue_binding.py | 6 +- ...t_observatory_portable_result_publisher.py | 173 ++- ...st_observatory_portable_run_definitions.py | 6 +- tests/test_observatory_portable_setup_api.py | 6 +- ...t_observatory_portable_setup_projection.py | 6 +- ...observatory_portable_worker_integration.py | 6 +- ...est_observatory_portable_worker_runtime.py | 12 +- tests/test_observatory_recorded_jobs.py | 55 + tests/test_observatory_transfer_storage.py | 232 ++++ tests/test_session_api.py | 80 +- tests/test_session_store.py | 18 +- 101 files changed, 9305 insertions(+), 2256 deletions(-) create mode 100644 apps/control-station/src/components/laboratory/LabReplayProgress.tsx create mode 100644 apps/control-station/src/components/observatory/FailedRunActions.tsx create mode 100644 apps/control-station/src/components/observatory/LabCopyActions.tsx create mode 100644 apps/control-station/src/components/storage/LabStorageSettings.tsx create mode 100644 apps/control-station/src/core/laboratory/prepareLabReplay.ts create mode 100644 apps/control-station/src/core/observatory/failedRunHistory.ts delete mode 100644 apps/control-station/src/core/observatory/useObservatoryLaboratorySetups.ts delete mode 100644 apps/control-station/src/core/observatory/useObservatoryRecordedJobs.ts create mode 100644 apps/control-station/src/core/storage/localLabPresentation.ts create mode 100644 apps/control-station/src/core/storage/localLabStorage.ts create mode 100644 apps/control-station/test/failedRunHistory.test.mjs create mode 100644 apps/control-station/test/labReplayPreparation.test.mjs delete mode 100644 apps/control-station/test/observatoryHooks.test.mjs create mode 100644 deploy/laboratory/Dockerfile create mode 100644 deploy/laboratory/README.md create mode 100644 deploy/laboratory/compose.yaml create mode 100644 deploy/laboratory/install_operator_link.py create mode 100644 deploy/laboratory/requirements.lock create mode 100644 deploy/laboratory/retire_fixed_lab_v1.ps1 create mode 100644 deploy/laboratory/verify_runtime.py create mode 100644 docs/LAB_AND_INSTALLER_STORAGE.md create mode 100644 src/k1link/laboratory/archive_store.py create mode 100644 src/k1link/laboratory/data_deletion.py create mode 100644 src/k1link/laboratory/deletion_coordinator.py create mode 100644 src/k1link/laboratory/deletion_inventory.py create mode 100644 src/k1link/laboratory/execution_authority.py create mode 100644 src/k1link/laboratory/local_presentations.py create mode 100644 src/k1link/laboratory/materialize_archive.py create mode 100644 src/k1link/laboratory/materialize_recorded_sources.py create mode 100644 src/k1link/laboratory/worker_gateway.py create mode 100644 src/k1link/laboratory/worker_recorded_sources.py create mode 100644 src/k1link/laboratory/worker_server.py create mode 100644 src/k1link/observatory/modular_model_assets.py create mode 100644 src/k1link/observatory/source_transport_lifecycle.py create mode 100644 src/k1link/observatory/transfer_space.py create mode 100644 src/k1link/web/local_storage_api.py create mode 100644 src/k1link/web/source_transfer_response.py create mode 100644 src/k1link/web/worker_laboratory_presentation.py create mode 100644 src/k1link/web/worker_laboratory_surface.py create mode 100644 tests/fixtures/observatory/retired-fixed-lab/README.md create mode 100644 tests/fixtures/observatory/retired-fixed-lab/observatory-portable-run-definitions.json create mode 100644 tests/fixtures/observatory/retired-fixed-lab/observatory-worker-runtime-candidates.json create mode 100644 tests/test_fixed_lab_retirement.py create mode 100644 tests/test_lab_data_deletion.py create mode 100644 tests/test_laboratory_archive_store.py create mode 100644 tests/test_laboratory_worker_gateway.py create mode 100644 tests/test_laboratory_worker_sources.py create mode 100644 tests/test_local_presentations.py create mode 100644 tests/test_observatory_transfer_storage.py diff --git a/AGENTS.md b/AGENTS.md index cdc0273f..5845b686 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,6 +5,17 @@ real device plugin investigates an owner-controlled XGRIDS/LixelKity K1 as a black-box sensor. Preserve the device, the host, the working LAN, raw evidence, and the boundary between Mission Core and vendor-specific integration code. +- Owner clarification (2026-11-08): LAB trash means permanent deletion of that + LAB's admitted files on Core and Worker, followed by removal from history. + Do not replace it with catalog-only hiding or leave unreachable result bytes. + Source recordings and files shared by retained LABs are separate owners. + Worker acknowledgement is mandatory; on failure keep a retryable history row. + Local-copy expiry/delete is a separate action that preserves history and Worker + results. Pin protects against expiry, not explicit full-LAB deletion. + A LAB module/registered component, its model, benchmark and shared inputs are + not disposable run output. Missing UI history alone is never evidence of junk; + establish ownership and dependencies before retiring an old experiment. + ## Single working directory — owner requirement, 2026-10-08 The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50), @@ -75,6 +86,55 @@ links to that record for monorepo, storage, resource and live-only telemetry rul retain the immutable algorithm result and human provenance separately. See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates. +## LAB placement — owner clarification, 2026-11-08 + +All supported laboratory execution, raw inputs, intermediate arrays and heavy +working directories belong to the portable Worker runtime. The operator Core is +a viewport: retain ready visual products, semantic maps/manual edits and bounded +metadata, never a silent local compute fallback. See +`docs/LAB_AND_INSTALLER_STORAGE.md` and `deploy/laboratory/README.md`. + +Canonical Ops policy: [MISSIONCOR-97 — Storage rules](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-97). +Read its current rules before a new LAB/AI data producer or storage migration; +keep current implementation distinct from the dated distributed-storage research. + +A LAB viewing result means a full playable recording with synchronized +segmentation/camera frames, 3D cuboids and timeline where the experiment provides +those layers. Catalog JSON, a screenshot or a textual report does not establish +playback acceptance. Preserve the current UI; do not add neural/narrative reports +or redesign LAB as part of storage migration. Later owner clarification on +8 November explicitly adds global Storage settings (configurable local LAB-copy +retention), offline pins, actual local availability and removal of local copies. +Run history must remain discoverable independently of replay compatibility or +local cache presence. These are requirements, not features already implemented +by the storage audit; see `outputs/storage-fresh-audit-20261108/REPORT.md`. +Verify real playback before retiring local working data; preserve accepted +recordings, Gaussians, semantic edits and original captures. + +The configurable LAB-copy TTL (default 30 days) applies exclusively to unpinned +local viewing copies in Mission Core, never to Worker experiments or their models. +Integrated/experimental model assets, installed executor packages/images, runtime +environments and experimental configurations are retained until a separate owner +decision consolidates the pipeline, even under `cache` or `derived`. Do not apply +LAB-copy TTL or absence-from-UI cleanup to them. A disposable transport package +means job input/output transfer bytes, not an executor/model distribution. Before retiring an intermediate +copy, verify publication/retry readers, shared owners and restoration of its exact +identity. See the 8 November intermediate-store rules in +`docs/STORAGE_RETENTION.md` and `outputs/intermediate-storage-review-20261108/REPORT.md`. + +Portable source/result transfer uses shared physical-disk reservations (2 GiB +free reserve), not fixed 8/4 GiB directory ceilings or model-count limits. +Source copies registered by admitted producers retire only after durable queue +consumers finish and exact originals remain available. HTTP reader locks span the +whole response. Preserve unknown paths, changed originals, shared filesystem +owners and pending publication/reconciliation. Source retirement is not a TTL. +Result closeout retains manifest/receipt for archive-backed retries; do not +readmit retired compute definitions merely to retire historical copies. +Use an explicit target allowlist for one-time historical cleanup and verify +unselected files; unknown old copies are not automatically adopted by a scan. +These rules do not change installed model/executor assets or viewing-copy TTL. +See the 9 November transfer lifecycle section of `docs/STORAGE_RETENTION.md`. + ## Non-negotiable safety boundaries - Default to non-mutating discovery or read-only operations. CoreBluetooth BLE diff --git a/apps/control-station/src/components/EnvironmentSettingsWindow.tsx b/apps/control-station/src/components/EnvironmentSettingsWindow.tsx index 67ce0de0..143e3c58 100644 --- a/apps/control-station/src/components/EnvironmentSettingsWindow.tsx +++ b/apps/control-station/src/components/EnvironmentSettingsWindow.tsx @@ -1,5 +1,6 @@ import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react"; import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings"; +import { useLabStorageSettings } from "./storage/LabStorageSettings"; import { roots, workspaces, workspacesForRoot } from "../productModel"; interface Props { @@ -16,7 +17,8 @@ const surfaces = environmentSurfaceIds.map(id => ({ actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id), })); export function EnvironmentSettingsWindow(props: Props) { - return props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })} onUpload={(id, itemId, file) => { if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна."); diff --git a/apps/control-station/src/components/laboratory/CanonicalResultRerunReplay.tsx b/apps/control-station/src/components/laboratory/CanonicalResultRerunReplay.tsx index 63d102ba..4389f638 100644 --- a/apps/control-station/src/components/laboratory/CanonicalResultRerunReplay.tsx +++ b/apps/control-station/src/components/laboratory/CanonicalResultRerunReplay.tsx @@ -6,7 +6,6 @@ import { useState, } from "react"; import { - ActivityIndicator, Button, Checker, ControlRow, @@ -35,7 +34,9 @@ import { import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay"; import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive"; import { laboratoryResultRerunProfile } from "../../core/observation/viewerProfile"; -import { resolveObservationSessionReplay } from "../../core/observation/useObservationSessions"; +import { prepareLabReplay, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay"; +import { LabReplayProgress } from "./LabReplayProgress"; +import { announceLabStorageChange } from "../../core/storage/localLabStorage"; import type { AIViewerLayer } from "../../core/observatory/aiComposition"; import { fetchLabViewProfile, @@ -216,6 +217,7 @@ export function CanonicalResultRerunReplay({ const [viewerStatus, setViewerStatus] = useState("idle"); const [launch, setLaunch] = useState(null); const [launchError, setLaunchError] = useState(null); + const [preparationProgress, setPreparationProgress] = useState({ phase: "checking", fraction: null }); const sceneDraftRef = useRef(sceneDraft); const previousSplitViewRef = useRef(splitView); const trackedLaunchSha256Ref = useRef(null); @@ -275,15 +277,10 @@ export function CanonicalResultRerunReplay({ setPlayback(null); setPlaybackController(null); setViewerStatus("idle"); - void resolveObservationSessionReplay(sessionId, { - signal: controller.signal, - maximumWaitMs: 30 * 60 * 1000, - onUpdate: () => undefined, - }).then(async (value) => ({ - base: value, - replay: await resolveReplay(resultId, value, { signal: controller.signal }), - })).then((value) => { - if (!controller.signal.aborted) setLaunch(value); + void prepareLabReplay(resultId, sessionId, resolveReplay, { + signal: controller.signal, onProgress: setPreparationProgress, + }).then((value) => { + if (!controller.signal.aborted) { setLaunch(value); announceLabStorageChange(); } }).catch((caught: unknown) => { if (!controller.signal.aborted) { setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна."); @@ -465,7 +462,9 @@ export function CanonicalResultRerunReplay({ emptyMessage="Слои результата недоступны." deckOverlays={presentationState === "loading" ? (
- +
) : undefined} transport={transport} diff --git a/apps/control-station/src/components/laboratory/LabReplayProgress.tsx b/apps/control-station/src/components/laboratory/LabReplayProgress.tsx new file mode 100644 index 00000000..9a15bc1f --- /dev/null +++ b/apps/control-station/src/components/laboratory/LabReplayProgress.tsx @@ -0,0 +1,10 @@ +import { Description, ProgressBar } from "@nodedc/ui-react"; +import { labReplayProgressView, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay"; + +export function LabReplayProgress({ progress }: { progress: Progress }) { + const view = labReplayProgressView(progress); + return
+ {view.text} + +
; +} diff --git a/apps/control-station/src/components/observatory/FailedRunActions.tsx b/apps/control-station/src/components/observatory/FailedRunActions.tsx new file mode 100644 index 00000000..1aa309b2 --- /dev/null +++ b/apps/control-station/src/components/observatory/FailedRunActions.tsx @@ -0,0 +1,29 @@ +import { useState } from "react"; +import { ConfirmationModal, Icon, IconButton } from "@nodedc/ui-react"; +import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs"; +import { deleteFailedRunProjection } from "../../core/observatory/failedRunHistory"; + +export function FailedRunActions({ job, onDeleted }: { + job: ObservatoryRecordedJob; + onDeleted: () => void; +}) { + const [open, setOpen] = useState(false); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + return <> + { setError(null); setOpen(true); }}> + + +

Попытка и её рабочие файлы будут удалены с этого устройства и Worker. Исходная запись сохранится.

+ {error ?

{error}

: null}} + confirmLabel="Удалить попытку" pendingLabel="Удаляем…" danger + onClose={() => { if (!pending) setOpen(false); }} + onConfirm={async () => { + setPending(true); setError(null); + try { await deleteFailedRunProjection(job); setOpen(false); onDeleted(); } + catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось удалить попытку."); } + finally { setPending(false); } + }} /> + ; +} diff --git a/apps/control-station/src/components/observatory/LabCopyActions.tsx b/apps/control-station/src/components/observatory/LabCopyActions.tsx new file mode 100644 index 00000000..ea7f58ac --- /dev/null +++ b/apps/control-station/src/components/observatory/LabCopyActions.tsx @@ -0,0 +1,71 @@ +import { useEffect, useRef, useState } from "react"; +import { ConfirmationModal, Icon, IconButton, ToastStack, type ToastItem } from "@nodedc/ui-react"; +import { announceLabStorageChange, pinLabCopy, prepareLocalLabCopy, removeLabCopy, + type LocalLabCopy } from "../../core/storage/localLabStorage"; +import { formatLocalLabSize } from "../../core/storage/localLabPresentation"; +import type { LabReplayProgress } from "../../core/laboratory/prepareLabReplay"; + +export type LabCopyProgress = LabReplayProgress; + +export function LabCopyActions({ id, sourceId, composition = false, copy, available, storageError, onProgress }: { + id: string; sourceId: string; composition?: boolean; copy?: LocalLabCopy; + available: boolean; storageError: string | null; + onProgress?: (value: LabReplayProgress | null) => void; +}) { + const [busy, setBusy] = useState<"download" | "pin" | "remove" | null>(null); + const [toasts, setToasts] = useState([]); + const [confirm, setConfirm] = useState(false); + const request = useRef(null); + const progressCallback = useRef(onProgress); + progressCallback.current = onProgress; + useEffect(() => () => { request.current?.abort(); progressCallback.current?.(null); }, []); + const status = storageError ?? (!available ? "Проверяем локальную копию" + : copy?.local ? `На этом устройстве · ${formatLocalLabSize(copy, true)}` + : "Загрузить запись на это устройство"); + async function perform(kind: "download" | "pin" | "remove", action: (signal: AbortSignal) => Promise) { + if (request.current) return; + const controller = new AbortController(); request.current = controller; + setBusy(kind); setToasts([]); + try { + await action(controller.signal); + if (!controller.signal.aborted) setConfirm(false); + } catch (reason) { + if (!controller.signal.aborted) setToasts([{ id: "lab-copy-error", tone: "error", + title: "Не удалось изменить локальную копию", + description: reason instanceof Error ? reason.message : "Повторите действие." }]); + } finally { + announceLabStorageChange(); + progressCallback.current?.(null); + request.current = null; + if (!controller.signal.aborted) setBusy(null); + } + } + const prepare = (signal: AbortSignal) => prepareLocalLabCopy(id, sourceId, composition, + { signal, onProgress: (value) => progressCallback.current?.(value) }); + const unavailable = !available || !!storageError; + return <> + void perform("download", prepare)}> + + + void perform("pin", async (signal) => { + if (!copy?.local && !copy?.pinned) await prepare(signal); + signal.throwIfAborted(); + await pinLabCopy(id, !copy?.pinned); + })}> + + + {copy?.local ? setConfirm(true)}> + + : null} + setToasts((items) => items.filter((item) => item.id !== key))} /> + { if (!busy) setConfirm(false); }} + onConfirm={() => perform("remove", () => removeLabCopy(id))} /> + ; +} diff --git a/apps/control-station/src/components/storage/LabStorageSettings.tsx b/apps/control-station/src/components/storage/LabStorageSettings.tsx new file mode 100644 index 00000000..8bc48405 --- /dev/null +++ b/apps/control-station/src/components/storage/LabStorageSettings.tsx @@ -0,0 +1,32 @@ +import { useEffect, useState } from "react"; +import { Button, SettingsCard, TextField, WindowFooterActions } from "@nodedc/ui-react"; +import { announceLabStorageChange, saveLabRetention, useLocalLabStorage } from "../../core/storage/localLabStorage"; + +export function useLabStorageSettings(open: boolean) { + const { data, error: loadError, refresh } = useLocalLabStorage(open); + const [days, setDays] = useState("30"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(false); + useEffect(() => { if (data) setDays(String(data.retention_days)); }, [data?.retention_days]); + const number = Number(days); + const valid = Number.isInteger(number) && number >= 1 && number <= 365; + const content = + { setDays(event.target.value); setSaved(false); }} /> +

После снятия булавки срок начинается заново. История запусков и результаты на Worker сохраняются.

+

Правило применяется к учтённым записям просмотра AI Inference. Исходные записи, Gaussian-сцены и разметка сохраняются отдельно.

+ {loadError || error ?

{error ?? loadError}

: saved ?

Настройки сохранены.

: null} +
; + const footer = + + + ; + return { id: "storage", label: "Хранилище", icon: "database" as const, content, footer }; +} diff --git a/apps/control-station/src/core/laboratory/prepareLabReplay.ts b/apps/control-station/src/core/laboratory/prepareLabReplay.ts new file mode 100644 index 00000000..e30c0608 --- /dev/null +++ b/apps/control-station/src/core/laboratory/prepareLabReplay.ts @@ -0,0 +1,57 @@ +import { resolveObservationSessionReplay } from "../observation/useObservationSessions"; +import type { ObservationSessionReplayLaunch } from "../observation/sessionArchive"; +import type { CanonicalLabReplayDescriptor } from "./canonicalLabReplay"; + +export interface LabReplayProgress { + phase: "checking" | "preparing" | "opening"; + fraction: number | null; +} +export type LabReplayResolver = (id: string, base: ObservationSessionReplayLaunch, + options: { signal: AbortSignal }) => Promise; + +/** Shared preparation for the eye, download and offline pin. Never runs inference. */ +export async function prepareLabReplay(id: string, sourceId: string, resolve: LabReplayResolver, + { signal, onProgress, fetcher }: { + signal: AbortSignal; + onProgress?: (progress: LabReplayProgress) => void; + fetcher?: typeof fetch; + }) { + const request = new AbortController(); + const abort = () => request.abort(); + signal.addEventListener("abort", abort, { once: true }); + const timer = globalThis.setTimeout(abort, 30 * 60 * 1000); + const publish = (progress: LabReplayProgress) => { + request.signal.throwIfAborted(); + onProgress?.(progress); + }; + try { + signal.throwIfAborted(); + publish({ phase: "checking", fraction: null }); + const base = await resolveObservationSessionReplay(sourceId, { + signal: request.signal, fetcher, maximumWaitMs: 30 * 60 * 1000, + onUpdate: (state) => publish({ phase: "preparing", fraction: state.progress }), + }); + publish({ phase: "preparing", fraction: null }); + const replay = await resolve(id, base, { signal: request.signal }); + request.signal.throwIfAborted(); + return { base, replay }; + } catch (error) { + if (request.signal.aborted && !signal.aborted) { + throw new Error("Подготовка записи заняла слишком много времени. Повторите загрузку."); + } + throw error; + } finally { + globalThis.clearTimeout(timer); + signal.removeEventListener("abort", abort); + } +} + +export function labReplayProgressView(progress: LabReplayProgress) { + const labels = { checking: "Проверка доступности записи", preparing: "Подготовка записи", + opening: "Открытие записи" }; + const value = progress.fraction === null || !Number.isFinite(progress.fraction) + ? undefined : Math.min(1, Math.max(0, progress.fraction)); + return { label: labels[progress.phase], value, + text: value === undefined ? labels[progress.phase] + : `${labels[progress.phase]} · ${Math.round(value * 100)}%` }; +} diff --git a/apps/control-station/src/core/observatory/catalog.ts b/apps/control-station/src/core/observatory/catalog.ts index 1f054e61..8eead209 100644 --- a/apps/control-station/src/core/observatory/catalog.ts +++ b/apps/control-station/src/core/observatory/catalog.ts @@ -170,9 +170,8 @@ function evidenceFromSession( `LAB-каталог вернул сессию ${session.id} без типизированной связи с источником.`, ); } - // Historical LABs retain their archive and replay adapters. Observatory is - // the portable-profile product; a familiar LAB label is not admission. - if (session.lab.replayCapability?.kind !== "portable-result-review") return null; + // History follows source identity. Playback admission remains independently + // validated below; an unavailable viewer must never erase a completed run. const recordedRun = observatoryRecordedRunBinding(session.id, session.lab); return { sessionId: session.id, @@ -303,12 +302,10 @@ async function readCatalogPages( throw new ObservatoryCatalogContractError("Каталог повторил сессию между страницами."); } seenIds.add(item.id); - // Do not accumulate legacy provenance while walking the shared catalog. - if (scope === "source" || item.lab?.replayCapability?.kind === "portable-result-review") { - items.push(item); - } else if (!item.lab) { + if (scope === "laboratory" && !item.lab) { throw new ObservatoryCatalogContractError("LAB-каталог вернул исходную сессию."); } + items.push(item); } cursor = page.nextCursor; if (cursor === null) return { items, hasMore: false }; diff --git a/apps/control-station/src/core/observatory/catalogMutations.ts b/apps/control-station/src/core/observatory/catalogMutations.ts index 6efd4988..1017f86d 100644 --- a/apps/control-station/src/core/observatory/catalogMutations.ts +++ b/apps/control-station/src/core/observatory/catalogMutations.ts @@ -1,3 +1,4 @@ +import type { ObservatoryEvidence } from "./catalog"; import type { ObservatoryRecordedRunBinding } from "./recordedRun"; const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; @@ -26,7 +27,7 @@ export class ObservatoryCatalogMutationError extends Error { } export async function renameObservatoryLabProjection( - binding: ObservatoryRecordedRunBinding, + binding: ObservatoryRecordedRunBinding | Pick, displayName: string, { signal, @@ -78,7 +79,7 @@ export async function renameObservatoryLabProjection( } export async function deleteObservatoryLabProjection( - binding: ObservatoryRecordedRunBinding, + binding: ObservatoryRecordedRunBinding | Pick, { signal, fetcher = globalThis.fetch, @@ -113,7 +114,16 @@ export async function deleteObservatoryLabProjection( } } -function admittedProjectionId(binding: ObservatoryRecordedRunBinding): string { +function admittedProjectionId(binding: ObservatoryRecordedRunBinding | Pick): string { + // Catalog ownership is independent of whether this client supports replay. + // The server verifies the typed LAB projection against its source rows. + if ("lab" in binding) { + if (!SAFE_SESSION_ID.test(binding.sessionId) || !binding.lab.labId + || !binding.lab.resultId || binding.lab.sourceSessionId === binding.sessionId) { + throw new ObservatoryCatalogMutationError("Выбранный результат не допущен к изменению каталога AI Inference."); + } + return binding.sessionId; + } const sessionId = binding.evidenceSessionId; const admittedViewer = ( binding.kind === "canonical-recorded-rerun" diff --git a/apps/control-station/src/core/observatory/failedRunHistory.ts b/apps/control-station/src/core/observatory/failedRunHistory.ts new file mode 100644 index 00000000..3f1f2f9d --- /dev/null +++ b/apps/control-station/src/core/observatory/failedRunHistory.ts @@ -0,0 +1,24 @@ +import type { ObservatoryRecordedJob, ObservatoryRecordedJobFetch } from "./recordedJobs"; + +export function failedRunDetail(job: Pick): string { + const message = job.terminalMessage ?? ""; + if (/source-member|source transport|Content-Length|camera-source/i.test(message)) { + return "Не удалось подготовить исходную запись"; + } + if (/assemble|export|presentation/i.test(message)) return "Не удалось собрать запись результата"; + if (/Docker Engine|container.*start|start.*container/i.test(message)) return "Не удалось запустить вычислительный контейнер"; + if (/exit 143|exit=143|cancel|interrupted/i.test(message)) return "Расчёт прерван до получения результата"; + if (/prepare/i.test(message)) return "Ошибка подготовки расчёта"; + return "Расчёт завершился ошибкой; готового результата нет"; +} + +export async function deleteFailedRunProjection( + job: Pick, + fetcher: ObservatoryRecordedJobFetch = globalThis.fetch, +): Promise { + if (!/^observatory-run-[a-f0-9]{32}$/.test(job.jobId) || job.state !== "failed" || job.resultId !== null) { + throw new Error("Удалить можно только ошибочную попытку без результата."); + } + const response = await fetcher(`/api/v1/observatory/ai-runs/${encodeURIComponent(job.jobId)}`, { method: "DELETE" }); + if (response.status !== 204) throw new Error("Не удалось удалить попытку из истории. Обновите список и повторите."); +} diff --git a/apps/control-station/src/core/observatory/useObservatoryLaboratorySetups.ts b/apps/control-station/src/core/observatory/useObservatoryLaboratorySetups.ts deleted file mode 100644 index 778e1bdc..00000000 --- a/apps/control-station/src/core/observatory/useObservatoryLaboratorySetups.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; - -import { - fetchObservatoryPortableLaboratorySetups, - preflightObservatoryLaboratorySetup, - selectableObservatorySetups, - type ObservatoryLaboratoryRunPreflight, - type ObservatoryLaboratorySetupCatalog, -} from "./laboratorySetups"; - -type SetupCatalogState = "idle" | "loading" | "ready" | "refreshing" | "error"; -export type SetupPreflightState = - | { readonly kind: "idle" } - | { readonly kind: "checking" } - | { readonly kind: "ready"; readonly value: ObservatoryLaboratoryRunPreflight } - | { readonly kind: "error"; readonly message: string }; - -export function useObservatoryLaboratorySetups(sourceSessionId: string) { - const [catalog, setCatalog] = useState(null); - const [state, setState] = useState("idle"); - const [error, setError] = useState(null); - const [selectedSetupId, setSelectedSetupId] = useState(""); - const [revision, setRevision] = useState(0); - const [preflight, setPreflight] = useState({ kind: "idle" }); - const requestSequence = useRef(0); - const preflightRequest = useRef(null); - const activeCatalog = catalog?.sourceSessionId === sourceSessionId ? catalog : null; - const selectableSetups = useMemo(() => selectableObservatorySetups(activeCatalog), [activeCatalog]); - const selectedSetup = selectableSetups.find((setup) => setup.setupId === selectedSetupId) ?? null; - const selectedDefinitionSha256 = selectedSetup?.runDefinition?.definitionSha256 ?? null; - - useEffect(() => { - preflightRequest.current?.abort(); - preflightRequest.current = null; - if (!sourceSessionId) { - setCatalog(null); - setState("idle"); - setError(null); - setSelectedSetupId(""); - setPreflight({ kind: "idle" }); - return; - } - const sequence = ++requestSequence.current; - const request = new AbortController(); - setState((current) => activeCatalog && current !== "idle" ? "refreshing" : "loading"); - setError(null); - setPreflight({ kind: "idle" }); - // Archived definitions belong to evidence, not to the calculation selector. - void fetchObservatoryPortableLaboratorySetups(sourceSessionId, { signal: request.signal }) - .then((next) => { - if (request.signal.aborted || requestSequence.current !== sequence) return; - setCatalog(next); - const selectable = selectableObservatorySetups(next); - setSelectedSetupId((current) => ( - selectable.some((setup) => setup.setupId === current) - ? current - : selectable[0]?.setupId ?? "" - )); - setState("ready"); - }) - .catch((caught: unknown) => { - if (request.signal.aborted || requestSequence.current !== sequence) return; - setState("error"); - setError(caught instanceof Error && caught.message.trim() - ? caught.message - : "Каталог профилей недоступен."); - }); - return () => request.abort(); - }, [revision, sourceSessionId]); - - useEffect(() => () => preflightRequest.current?.abort(), []); - - useEffect(() => { - preflightRequest.current?.abort(); - preflightRequest.current = null; - setPreflight((current) => current.kind === "idle" ? current : { kind: "idle" }); - }, [selectedSetupId, sourceSessionId, selectedDefinitionSha256]); - - const selectSetup = useCallback((setupId: string) => { - preflightRequest.current?.abort(); - preflightRequest.current = null; - setSelectedSetupId(setupId); - setPreflight({ kind: "idle" }); - }, []); - - const refresh = useCallback(() => setRevision((value) => value + 1), []); - - const check = useCallback(async () => { - if (!sourceSessionId || !selectedSetup || preflight.kind === "checking") return; - preflightRequest.current?.abort(); - const request = new AbortController(); - preflightRequest.current = request; - setPreflight({ kind: "checking" }); - try { - const value = await preflightObservatoryLaboratorySetup( - sourceSessionId, - selectedSetup, - { signal: request.signal }, - ); - if (request.signal.aborted || preflightRequest.current !== request) return; - setPreflight({ kind: "ready", value }); - } catch (caught) { - if (request.signal.aborted || preflightRequest.current !== request) return; - setPreflight({ - kind: "error", - message: caught instanceof Error && caught.message.trim() - ? caught.message - : "Не удалось проверить возможность запуска.", - }); - } finally { - if (preflightRequest.current === request) preflightRequest.current = null; - } - }, [preflight.kind, selectedSetup, sourceSessionId]); - - useEffect(() => { - if (state !== "ready" || !selectedSetup || preflight.kind !== "idle") return; - void check(); - }, [check, preflight.kind, selectedSetup, state]); - - return { - catalog: activeCatalog, - selectableSetups, - state, - error, - selectedSetupId: selectedSetup?.setupId ?? "", - selectedSetup, - selectSetup, - refresh, - preflight, - check, - }; -} diff --git a/apps/control-station/src/core/observatory/useObservatoryRecordedJobs.ts b/apps/control-station/src/core/observatory/useObservatoryRecordedJobs.ts deleted file mode 100644 index 9f0a7755..00000000 --- a/apps/control-station/src/core/observatory/useObservatoryRecordedJobs.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from "react"; -import { fetchRecordedProgress, type RecordedProgressView } from "./recordedProgress"; - -import { - fetchObservatoryRecordedJobs, - retryObservatoryRecordedJobPublication, - submitObservatoryRecordedJob, - type ObservatoryRecordedJob, -} from "./recordedJobs"; - -type RecordedJobsState = - | "idle" - | "loading" - | "ready" - | "refreshing" - | "submitting" - | "retrying-publication" - | "error"; - -interface JobSnapshot { - readonly selectionKey: string; - readonly jobs: readonly ObservatoryRecordedJob[]; - readonly state: RecordedJobsState; - readonly error: string | null; - readonly progress?: RecordedProgressView | null; -} -const EMPTY_JOBS = [] as const; -const OPEN_STATES = new Set([ - "accepted", "queued", "claimed", "running", "paused", "preemption-pending", - "reconciliation-required", -]); -const POLL_INTERVAL_MS = 1_500; - -export function useObservatoryRecordedJobs( - sourceSessionId: string, - setupId: string, - definitionSha256: string, -) { - const selectionKey = JSON.stringify([sourceSessionId, setupId, definitionSha256]); - const [snapshot, setSnapshot] = useState({ - selectionKey: "", jobs: EMPTY_JOBS, state: "idle", error: null, - }); - const [revision, setRevision] = useState(0); - const requestRef = useRef(null); - const requestSequence = useRef(0); - const idempotencyKeys = useRef(new Map()); - const observedJobId = useRef(null); - const hasSelection = Boolean(sourceSessionId && setupId && definitionSha256); - // A source/profile change must not display even one render of the previous queue. - const current = snapshot.selectionKey === selectionKey ? snapshot : null; - const jobs = current?.jobs ?? EMPTY_JOBS; - const state = current?.state ?? (hasSelection ? "loading" : "idle"); - const error = current?.error ?? null; - - useEffect(() => { - requestRef.current?.abort(); - requestRef.current = null; - if (!hasSelection) { - setSnapshot({ selectionKey, jobs: EMPTY_JOBS, state: "idle", error: null }); - return; - } - const sequence = ++requestSequence.current; - const request = new AbortController(); - requestRef.current = request; - setSnapshot({ - selectionKey, jobs, - state: jobs.length > 0 ? "refreshing" : "loading", error: null, - progress: current?.progress ?? null, - }); - void fetchObservatoryRecordedJobs(sourceSessionId, setupId, { - definitionSha256, signal: request.signal, - }).then(async (next) => { - if (request.signal.aborted || requestSequence.current !== sequence) return; - const pending = next.find((job) => OPEN_STATES.has(job.state)); - const progress = pending - ? await fetchRecordedProgress(pending, { signal: request.signal }).catch(() => null) - : null; - if (request.signal.aborted || requestSequence.current !== sequence) return; - if (pending) observedJobId.current = pending.jobId; - setSnapshot({ selectionKey, jobs: next, state: "ready", error: null, progress }); - }).catch((caught: unknown) => { - if (request.signal.aborted || requestSequence.current !== sequence) return; - setSnapshot({ - selectionKey, jobs, state: "error", - error: caught instanceof Error && caught.message.trim() - ? caught.message - : "Очередь расчётов недоступна.", - }); - }).finally(() => { - if (requestRef.current === request) requestRef.current = null; - }); - return () => request.abort(); - }, [revision, selectionKey]); - - useEffect(() => () => requestRef.current?.abort(), []); - - const latestJob = jobs[0] ?? null; - const activeJob = jobs.find((job) => OPEN_STATES.has(job.state)) ?? null; - const publicationPending = jobs.some((job) => job.publication.state === "pending"); - // Do not promote historical terminal logs to a new operator action's error. - const computationFailed = latestJob?.state === "failed" - && latestJob.jobId === observedJobId.current; - - useEffect(() => { - if ((state !== "ready" && state !== "error") || (!activeJob && !publicationPending)) return; - const timer = globalThis.setTimeout( - () => setRevision((value) => value + 1), - POLL_INTERVAL_MS, - ); - return () => globalThis.clearTimeout(timer); - }, [activeJob, publicationPending, revision, state]); - - useEffect(() => { - if (!latestJob || activeJob) return; - idempotencyKeys.current.delete(selectionKey); - }, [activeJob, latestJob, selectionKey]); - - const refresh = useCallback(() => setRevision((value) => value + 1), []); - - const submit = useCallback(async ( - portableBinding: { - readonly definitionSha256: string; - readonly checkSha256: string; - } | null = null, - ): Promise => { - if (!hasSelection || state !== "ready" - || portableBinding?.definitionSha256 !== definitionSha256 - || publicationPending || latestJob?.publication.state === "failed") return null; - if (activeJob) return activeJob; - requestRef.current?.abort(); - const request = new AbortController(); - requestRef.current = request; - const key = idempotencyKeys.current.get(selectionKey) ?? createIdempotencyKey(); - idempotencyKeys.current.set(selectionKey, key); - setSnapshot({ selectionKey, jobs, state: "submitting", error: null }); - try { - const job = await submitObservatoryRecordedJob( - sourceSessionId, setupId, key, portableBinding, { signal: request.signal }, - ); - if (request.signal.aborted || requestRef.current !== request) return null; - observedJobId.current = job.jobId; - setSnapshot({ - selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)], - state: "ready", error: null, - }); - return job; - } catch (caught) { - if (request.signal.aborted || requestRef.current !== request) return null; - setSnapshot({ - selectionKey, jobs, state: "error", - error: caught instanceof Error && caught.message.trim() - ? caught.message - : "Не удалось поставить расчёт в очередь.", - }); - return null; - } finally { - if (requestRef.current === request) requestRef.current = null; - } - }, [activeJob, definitionSha256, hasSelection, jobs, latestJob, - publicationPending, selectionKey, setupId, sourceSessionId, state]); - - const retryPublication = useCallback(async (): Promise => { - if (!latestJob || latestJob.publication.state !== "failed" - || state === "retrying-publication") return null; - requestRef.current?.abort(); - const request = new AbortController(); - requestRef.current = request; - setSnapshot({ selectionKey, jobs, state: "retrying-publication", error: null }); - try { - const job = await retryObservatoryRecordedJobPublication(latestJob.jobId, { - signal: request.signal, - }); - if (request.signal.aborted || requestRef.current !== request) return null; - setSnapshot({ - selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)], - state: "ready", error: null, - }); - return job; - } catch (caught) { - if (request.signal.aborted || requestRef.current !== request) return null; - setSnapshot({ - selectionKey, jobs, state: "error", - error: caught instanceof Error && caught.message.trim() - ? caught.message - : "Не удалось повторить публикацию результата.", - }); - return null; - } finally { - if (requestRef.current === request) requestRef.current = null; - } - }, [jobs, latestJob, selectionKey, state]); - - return { - jobs, latestJob, activeJob, publicationPending, computationFailed, - progress: current?.progress ?? null, - state, error, refresh, submit, retryPublication, - }; -} - -function createIdempotencyKey(): string { - const entropy = typeof globalThis.crypto?.randomUUID === "function" - ? globalThis.crypto.randomUUID() - : `${Date.now().toString(36)}-${Math.random().toString(16).slice(2)}`; - return `observatory-ui:${entropy}`; -} - -export type ObservatoryRecordedJobsController = ReturnType; diff --git a/apps/control-station/src/core/storage/localLabPresentation.ts b/apps/control-station/src/core/storage/localLabPresentation.ts new file mode 100644 index 00000000..b5eba74b --- /dev/null +++ b/apps/control-station/src/core/storage/localLabPresentation.ts @@ -0,0 +1,11 @@ +import type { LocalLabCopy } from "./localLabStorage"; + +export function formatLocalLabSize(copy: LocalLabCopy | undefined, available: boolean) { + if (!available) return "размер уточняется"; + if (!copy?.local) return "0 Б на устройстве"; + const units = ["Б", "КБ", "МБ", "ГБ"]; + let value = copy.bytes; + let unit = 0; + while (value >= 1000 && unit < units.length - 1) { value /= 1000; unit += 1; } + return `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 1 }).format(value)} ${units[unit]}`; +} diff --git a/apps/control-station/src/core/storage/localLabStorage.ts b/apps/control-station/src/core/storage/localLabStorage.ts new file mode 100644 index 00000000..1d94e2c4 --- /dev/null +++ b/apps/control-station/src/core/storage/localLabStorage.ts @@ -0,0 +1,73 @@ +import { useCallback, useEffect, useState } from "react"; +import { prepareLabReplay, type LabReplayProgress } from "../laboratory/prepareLabReplay"; +import { resolveAICompositionReplay, resolveCanonicalLabReplay } from "../laboratory/canonicalLabReplay"; + +export interface LocalLabCopy { + local: boolean; + pinned: boolean; + bytes: number; + last_used: number; +} +export interface LocalLabStorage { + retention_days: number; + entries: Readonly>; +} +const endpoint = "/api/v1/storage/laboratory"; + +async function request(path = "", method = "GET", body?: unknown): Promise { + const response = await fetch(`${endpoint}${path}`, { + method, credentials: "same-origin", cache: "no-store", + headers: { "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + const value = await response.json(); + if (!response.ok) throw new Error(value.detail ?? "Хранилище недоступно."); + if (!Number.isInteger(value.retention_days) || value.retention_days < 1 + || value.retention_days > 365 || !value.entries || typeof value.entries !== "object" + || Array.isArray(value.entries)) throw new Error("Некорректные настройки хранения."); + for (const copy of Object.values(value.entries) as LocalLabCopy[]) { + if (typeof copy.local !== "boolean" || typeof copy.pinned !== "boolean" + || !Number.isSafeInteger(copy.bytes) || copy.bytes < 0 + || !Number.isFinite(copy.last_used)) throw new Error("Некорректное состояние локальной копии."); + } + return value; +} +export const saveLabRetention = (days: number) => request("/policy", "PUT", { retention_days: days }); +export const pinLabCopy = (id: string, pinned: boolean) => request(`/copies/${encodeURIComponent(id)}/pin`, "PUT", { pinned }); +export const removeLabCopy = (id: string) => request(`/copies/${encodeURIComponent(id)}`, "DELETE"); + +export async function prepareLocalLabCopy(id: string, sourceId: string, composition: boolean, + options: { signal: AbortSignal; onProgress?: (value: LabReplayProgress) => void }) { + return prepareLabReplay(id, sourceId, (resultId, base, request) => composition + ? resolveAICompositionReplay(resultId, base, request) + : resolveCanonicalLabReplay(resultId, base, { ...request, + sourceKind: id.startsWith("m49-tgs") ? "portable-tgs" + : /^ai-layer-(rf-detr|object-distance)-/.test(id) ? "portable-objects" : "portable-semantic" }), + options); +} + +export function useLocalLabStorage(enabled = true) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const refresh = useCallback(async () => { + try { setData(await request()); setError(null); } + catch (reason) { setError(reason instanceof Error ? reason.message : "Хранилище недоступно."); } + }, []); + useEffect(() => { + if (!enabled) return; + void refresh(); + const update = () => void refresh(); + window.addEventListener("focus", update); + window.addEventListener("lab-local-storage-changed", update); + const interval = window.setInterval(update, 15000); + return () => { + window.clearInterval(interval); + window.removeEventListener("focus", update); + window.removeEventListener("lab-local-storage-changed", update); + }; + }, [enabled, refresh]); + return { data, error, refresh }; +} +export function announceLabStorageChange() { + window.dispatchEvent(new Event("lab-local-storage-changed")); +} diff --git a/apps/control-station/src/styles/m4-replay-threat.css b/apps/control-station/src/styles/m4-replay-threat.css index c3d8303b..ca1daa0a 100644 --- a/apps/control-station/src/styles/m4-replay-threat.css +++ b/apps/control-station/src/styles/m4-replay-threat.css @@ -507,3 +507,24 @@ border: 1px solid rgb(var(--nodedc-accent-rgb)); background: transparent; } + +/* The LAB stage and list share measured preparation feedback. Controls are canonical. */ +.lab-replay-progress { + --nodedc-progress-height: calc(var(--nodedc-space-2) * 0.7); + --nodedc-description-font-size: calc(var(--nodedc-font-size-sm) * 0.85); + display: grid; + gap: var(--nodedc-space-3, 0.75rem); + width: min(24rem, 100%); + min-width: 0; +} +.observatory-evidence-card > .lab-replay-progress { + width: min(16rem, 22vw); +} + +@container observatory-session (max-width: 48rem) { + .observatory-evidence-card > .lab-replay-progress { + grid-column: 2 / -1; + grid-row: 2; + width: 100%; + } +} diff --git a/apps/control-station/src/workspaces/observatory/ObservatoryWorkspace.tsx b/apps/control-station/src/workspaces/observatory/ObservatoryWorkspace.tsx index db966aaf..e362c227 100644 --- a/apps/control-station/src/workspaces/observatory/ObservatoryWorkspace.tsx +++ b/apps/control-station/src/workspaces/observatory/ObservatoryWorkspace.tsx @@ -17,6 +17,12 @@ import { import { CanonicalVegetationRerunReplay } from "../../components/laboratory/CanonicalVegetationRerunReplay"; import { AICompositionReplay } from "../../components/laboratory/AICompositionReplay"; import { PortableResultReplay } from "../../components/laboratory/PortableResultReplay"; +import { useLocalLabStorage } from "../../core/storage/localLabStorage"; +import { FailedRunActions } from "../../components/observatory/FailedRunActions"; +import { failedRunDetail } from "../../core/observatory/failedRunHistory"; +import { LabCopyActions, type LabCopyProgress as CopyProgress } from "../../components/observatory/LabCopyActions"; +import { LabReplayProgress } from "../../components/laboratory/LabReplayProgress"; +import { formatLocalLabSize } from "../../core/storage/localLabPresentation"; import { AIConfigurationWindow } from "../../components/observatory/AIConfigurationWindow"; import type { ObservationSessionStatus } from "../../core/observation/sessionArchive"; import { createObservationReplayCoordinator } from "../../core/observation/replayCoordinator"; @@ -273,7 +279,7 @@ function aiJobStageDetail( recordingDurationSeconds: number, ): string { if (job.state === "failed") { - return "Не удалось запустить модель. Конфигурацию можно отправить повторно"; + return failedRunDetail(job); } if (job.publication.state === "failed") { return "Результат рассчитан, но не сохранён в AI Inference"; @@ -299,23 +305,6 @@ function aiJobStageDetail( return "Собираем, передаём и сохраняем результат"; } -function presentAIJob(job: ObservatoryRecordedJob): boolean { - if (job.state === "failed") return true; - if (job.publication.state === "pending" || job.publication.state === "failed") return true; - return job.state !== "succeeded"; -} - -function presentLatestAIJobs( - jobs: readonly ObservatoryRecordedJob[], -): readonly ObservatoryRecordedJob[] { - const seenSetups = new Set(); - return jobs.filter((job) => { - if (seenSetups.has(job.setupId)) return false; - seenSetups.add(job.setupId); - return presentAIJob(job); - }); -} - function compositionProgressPercent( run: AICompositionRun, progress: Readonly>, @@ -344,6 +333,7 @@ export function ObservatoryWorkspace({ definition: WorkspaceDefinition; }) { const controller = useObservatoryCatalog(); + const localStorage = useLocalLabStorage(); const [selectedSessionId, setSelectedSessionId] = useState(""); const [aiConfigurationOpen, setAIConfigurationOpen] = useState(false); const [evidenceSortDirection, setEvidenceSortDirection] = useState("newest"); @@ -360,6 +350,9 @@ export function ObservatoryWorkspace({ ObservatoryMutationReconciliation | null >(null); const overviewRef = useRef(null); + const [copyProgress, setCopyProgress] = useState>({}); + const updateCopyProgress = (id: string, value: CopyProgress | null) => + setCopyProgress((current) => ({ ...current, [id]: value })); const replayCoordinatorRef = useRef(createObservationReplayCoordinator()); const refreshedPublishedJobRef = useRef(null); const items = controller.catalog?.items ?? EMPTY_OBSERVATORY_ITEMS; @@ -400,8 +393,9 @@ export function ObservatoryWorkspace({ const compositionJobIds = useMemo(() => new Set( presentedCompositionRuns.flatMap((run) => run.jobIds), ), [presentedCompositionRuns]); - const presentedAIJobs = presentLatestAIJobs(aiJobsController.jobs).filter( - (job) => !compositionJobIds.has(job.jobId), + const presentedAIJobs = aiJobsController.jobs.filter( + (job) => !compositionJobIds.has(job.jobId) + && !presentedEvidence.some((evidence) => evidence.lab.resultId === job.resultId), ); const presentedRows = useMemo(() => { const rows: ObservatoryEvidenceRow[] = [ @@ -509,7 +503,6 @@ export function ObservatoryWorkspace({ }, [closeReplay]); const openRename = useCallback((evidence: ObservatoryEvidence) => { - if (!evidence.recordedRun) return; setCompositionRenameTarget(null); setCompositionDeleteTarget(null); setDeleteTarget(null); @@ -520,7 +513,6 @@ export function ObservatoryWorkspace({ }, []); const openDelete = useCallback((evidence: ObservatoryEvidence) => { - if (!evidence.recordedRun) return; setCompositionRenameTarget(null); setCompositionDeleteTarget(null); setRenameTarget(null); @@ -567,7 +559,7 @@ export function ObservatoryWorkspace({ } return; } - if (!renameTarget?.recordedRun || mutationPending !== null) return; + if (!renameTarget || mutationPending !== null) return; const requestedDisplayName = renameValue.trim(); const reconciliation: ObservatoryMutationReconciliation = { kind: "rename", @@ -579,7 +571,7 @@ export function ObservatoryWorkspace({ setMutationReconciliation(reconciliation); try { const result = await renameObservatoryLabProjection( - renameTarget.recordedRun, + renameTarget, renameValue, ); controller.applyEvidenceRename(result.sessionId, result.displayName); @@ -621,7 +613,7 @@ export function ObservatoryWorkspace({ } return; } - if (!deleteTarget?.recordedRun || mutationPending !== null) return; + if (!deleteTarget || mutationPending !== null) return; const reconciliation: ObservatoryMutationReconciliation = { kind: "delete", sessionId: deleteTarget.sessionId, @@ -639,7 +631,7 @@ export function ObservatoryWorkspace({ closeReplay(); }); } - await deleteObservatoryLabProjection(deleteTarget.recordedRun); + await deleteObservatoryLabProjection(deleteTarget); controller.applyEvidenceDeletion(deleteTarget.sessionId); setDeleteTarget(null); setMutationReconciliation(null); @@ -800,7 +792,7 @@ export function ObservatoryWorkspace({
СВЯЗАННЫЕ РЕЗУЛЬТАТЫ -

Лабораторные доказательства

+

История запусков

0 ? "accent" : "neutral"}> @@ -852,15 +844,21 @@ export function ObservatoryWorkspace({
) : null} {run.state === "ready" - ? formatTimestamp(row.timestamp) + ? `${formatTimestamp(row.timestamp)} / ${formatLocalLabSize(localStorage.data?.entries[run.runId], !!localStorage.data && !localStorage.error)}` : `${compositionStage(run, aiJobsController.progress)} · ${formatTimestamp(row.timestamp)}`} {active ? ( {Math.round(progressPercent)}% ) : failed ? Ошибка : null} + + {copyProgress[run.runId] ? : null}
{run.state === "ready" ? ( <> + updateCopyProgress(run.runId, value)} + copy={localStorage.data?.entries[run.runId]} available={!!localStorage.data} + storageError={localStorage.error} /> openCompositionDelete(run)} @@ -927,6 +925,9 @@ export function ObservatoryWorkspace({ {active ? ( {Math.round(progressPercent)}% ) : failed ? Ошибка : null} + {job.state === "failed" && job.resultId === null ? ( + + ) : null}
); @@ -946,11 +947,19 @@ export function ObservatoryWorkspace({ )} {formatTimestamp(row.timestamp)} + {evidence.recordedRun?.kind === "portable-result-review" + ? ` / ${formatLocalLabSize(localStorage.data?.entries[evidence.lab.resultId], !!localStorage.data && !localStorage.error)}` : ""} + {!evidence.recordedRun ? " · Просмотр этого формата пока недоступен" : ""} + {copyProgress[evidence.lab.resultId] ? : null}
- {evidence.recordedRun ? ( - <> + <> + {evidence.recordedRun?.kind === "portable-result-review" ? updateCopyProgress(evidence.lab.resultId, value)} + copy={localStorage.data?.entries[evidence.lab.resultId]} available={!!localStorage.data} + storageError={localStorage.error} /> : null} openDelete(evidence)} @@ -963,7 +972,7 @@ export function ObservatoryWorkspace({ > - : } - + : null} - ) : null}
@@ -1161,23 +1169,23 @@ export function ObservatoryWorkspace({

- Будут удалены только каталожная проекция {deleteTarget?.label ?? compositionDeleteTarget?.displayName ?? compositionDeleteTarget?.presentation.configurationLabel} - {" "}и её отображаемое название в AI Inference. + Будут удалены LAB {deleteTarget?.label ?? compositionDeleteTarget?.displayName ?? compositionDeleteTarget?.presentation.configurationLabel} + {" "}и её данные на этом устройстве и на Worker, включая закреплённую локальную копию.

- Исходная сессия, запечатанный лабораторный результат и файлы доказательств - останутся неизменными. + Исходная запись и данные, используемые другими LAB, сохранятся. + Отменить удаление нельзя.

{mutationError ? (

{mutationError}

) : null} ) : null} - confirmLabel="Удалить из AI Inference" + confirmLabel="Удалить LAB" pendingLabel="Удаляем…" danger onClose={() => { diff --git a/apps/control-station/test/failedRunHistory.test.mjs b/apps/control-station/test/failedRunHistory.test.mjs new file mode 100644 index 00000000..8a3ecd40 --- /dev/null +++ b/apps/control-station/test/failedRunHistory.test.mjs @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import { before, after, test } from "node:test"; +import { createServer } from "./support/vite-server.mjs"; +let server, api; +before(async () => { server = await createServer({ appType: "custom", logLevel: "silent", server: { middlewareMode: true } }); api = await server.ssrLoadModule("/src/core/observatory/failedRunHistory.ts"); }); +after(async () => { await server?.close(); }); +test("failed history distinguishes source, container and result assembly failures without exposing logs", () => { + assert.equal(api.failedRunDetail({ terminalMessage: "step camera-source exited with code 1" }), "Не удалось подготовить исходную запись"); + assert.equal(api.failedRunDetail({ terminalMessage: "step assemble exited with code 1" }), "Не удалось собрать запись результата"); + assert.equal(api.failedRunDetail({ terminalMessage: "Docker Engine returned 500" }), "Не удалось запустить вычислительный контейнер"); +}); +test("history removal rejects active and successful work before request", async () => { + const job = { jobId: `observatory-run-${"a".repeat(32)}`, state: "failed", resultId: null }; + let calls=0; + const fetcher = async () => { calls++; return new Response(null,{status:204}); }; + await assert.rejects(api.deleteFailedRunProjection({...job,state:"running"},fetcher)); + await assert.rejects(api.deleteFailedRunProjection({...job,resultId:"result"},fetcher)); + assert.equal(calls,0); + await api.deleteFailedRunProjection(job,fetcher); + assert.equal(calls,1); +}); diff --git a/apps/control-station/test/labReplayPreparation.test.mjs b/apps/control-station/test/labReplayPreparation.test.mjs new file mode 100644 index 00000000..23939439 --- /dev/null +++ b/apps/control-station/test/labReplayPreparation.test.mjs @@ -0,0 +1,55 @@ +import assert from "node:assert/strict"; +import { after, before, test } from "node:test"; +import { createServer } from "./support/vite-server.mjs"; +let server, prepareLabReplay, labReplayProgressView, formatLocalLabSize; +before(async () => { + server = await createServer({ appType: "custom", logLevel: "silent", server: { middlewareMode: true } }); + ({ prepareLabReplay, labReplayProgressView } = await server.ssrLoadModule("/src/core/laboratory/prepareLabReplay.ts")); + ({ formatLocalLabSize } = await server.ssrLoadModule("/src/core/storage/localLabPresentation.ts")); +}); +after(async () => server?.close()); +function baseResponse() { + const url = "/api/v1/observation-sessions/session-1/recording.rrd"; + return Response.json({ schema_version: "missioncore.observation-session-replay/v2", launch: { + kind: "rerun-recording", session_id: "session-1", source_url: url, + viewer_source_url: `${url}?generation=${"a".repeat(64)}`, media_type: "application/vnd.rerun.rrd", + timeline: "session_time", timeline_start_seconds: 0, timeline_end_seconds: 10, + seekable: true, byte_length: 100, sha256: "a".repeat(64), + playback: { speed: 1, loop: false }, media_sources: [], + } }); +} +test("copy preparation binds the selected source then builds one replay without inference", async () => { + const stages = [], calls = []; + const value = await prepareLabReplay("result-1", "session-1", async (id, base, options) => { + calls.push(id); assert.equal(base.sessionId, "session-1"); assert.equal(options.signal.aborted, false); + return { byteLength: 245 }; + }, { signal: new AbortController().signal, onProgress: p => stages.push(p), + fetcher: async url => { calls.push(url); return baseResponse(); } }); + assert.deepEqual(calls, ["/api/v1/observation-sessions/session-1/replay", "result-1"]); + assert.deepEqual(stages, [{ phase: "checking", fraction: null }, { phase: "preparing", fraction: null }]); + assert.equal(value.replay.byteLength, 245); +}); +test("source failure does not start assembly or publish a success stage", async () => { + let assembled = false; + await assert.rejects(prepareLabReplay("result", "session-1", async () => { assembled = true; }, { + signal: new AbortController().signal, fetcher: async () => Response.json({detail:"offline"}, {status:503}), + })); + assert.equal(assembled, false); +}); +test("closing preparation aborts its request and suppresses stale completion", async () => { + const owner = new AbortController(); let requestSignal; + await assert.rejects(prepareLabReplay("result", "session-1", async (_, __, options) => { + requestSignal = options.signal; owner.abort(); return { byteLength: 1 }; + }, { signal: owner.signal, fetcher: async () => baseResponse() }), { name: "AbortError" }); + assert.equal(requestSignal.aborted, true); +}); +test("unknown progress stays indeterminate; measured opening progress has a percentage", () => { + assert.equal(labReplayProgressView({ phase: "preparing", fraction: null }).value, undefined); + assert.equal(labReplayProgressView({ phase: "opening", fraction: .47 }).text, "Открытие записи · 47%"); + assert.equal(labReplayProgressView({ phase: "opening", fraction: NaN }).value, undefined); +}); +test("removed copy shows zero even when old metadata retains a size; unknown is distinct", () => { + assert.equal(formatLocalLabSize({local:false, bytes:425918766}, true), "0 Б на устройстве"); + assert.equal(formatLocalLabSize(undefined, false), "размер уточняется"); + assert.equal(formatLocalLabSize({local:true, bytes:425918766}, true), "425,9 МБ"); +}); diff --git a/apps/control-station/test/observatoryCatalog.test.mjs b/apps/control-station/test/observatoryCatalog.test.mjs index 6113830d..127fbef5 100644 --- a/apps/control-station/test/observatoryCatalog.test.mjs +++ b/apps/control-station/test/observatoryCatalog.test.mjs @@ -222,7 +222,7 @@ test("Observatory exposes bounded-window uncertainty without inventing a broken ); }); -test("historical canonical replay stays out of Observatory without modifying its archive record", () => { +test("historical canonical replay remains in source history without modifying its archive record", () => { const canonicalResultId = `lab-v1-vegetation-shadow-${"8".repeat(64)}`; const canonical = evidence( canonicalResultId, @@ -252,12 +252,12 @@ test("historical canonical replay stays out of Observatory without modifying its [canonical], ); - assert.deepEqual(catalog.items[0].evidence, []); - assert.equal(catalog.window.laboratoryCount, 0); + assert.equal(catalog.items[0].evidence[0].recordedRun.kind, "canonical-recorded-rerun"); + assert.equal(catalog.window.laboratoryCount, 1); assert.deepEqual(canonical, before); }); -test("only admitted portable evidence is visible regardless of LAB label, age or installed version", () => { +test("history retains unsupported formats while playback admission remains explicit", () => { const legacy = evidence("legacy", "source", "2026-09-03T13:00:00Z"); legacy.lab.labId = "LAB M4.9T5"; legacy.lab.replayCapability = null; @@ -267,9 +267,9 @@ test("only admitted portable evidence is visible regardless of LAB label, age or const catalog = buildObservatoryCatalog( [source("source", "2026-07-19T10:00:00Z")], [legacy, historical, current], ); - assert.deepEqual(catalog.items[0].evidence.map((item) => item.sessionId), ["new-portable", "old-portable"]); - assert.equal(catalog.window.laboratoryCount, 2); - assert.equal(findObservatoryEvidence(catalog, "legacy"), null); + assert.deepEqual(catalog.items[0].evidence.map((item) => item.sessionId), ["legacy", "new-portable", "old-portable"]); + assert.equal(catalog.window.laboratoryCount, 3); + assert.equal(findObservatoryEvidence(catalog, "legacy").recordedRun, null); }); test("a malformed portable binding errors instead of silently disappearing as legacy", () => { @@ -325,7 +325,8 @@ test("500 sources and later-page results are searchable metadata, with no archiv } }); assert.equal(calls.length, 7); assert.equal(catalog.items.length, 500); - assert.equal(catalog.window.laboratoryCount, 1); + assert.equal(catalog.window.laboratoryCount, 102); + assert.equal(catalog.items.find(item => item.source.id === "source-0").evidence.length, 101); assert.equal(catalog.window.sourceLimitReached, false); assert.equal(catalog.window.laboratoryLimitReached, false); assert.equal(catalog.items.find((item) => item.source.id === "source-499").evidence[0].sessionId, "portable-after-legacy"); diff --git a/apps/control-station/test/observatoryCatalogMutations.test.mjs b/apps/control-station/test/observatoryCatalogMutations.test.mjs index 54e50768..e3725148 100644 --- a/apps/control-station/test/observatoryCatalogMutations.test.mjs +++ b/apps/control-station/test/observatoryCatalogMutations.test.mjs @@ -121,3 +121,14 @@ test("Observatory mutations reject response drift and preserve API detail", asyn && error.message === "Проекция не принадлежит AI Inference.", ); }); + +test("legacy LAB projection can be removed without a replay capability", async () => { + let called = false; + await deleteObservatoryLabProjection({ sessionId: "lab-old", lab: { + labId: "LAB E21", sourceSessionId: "source", resultId: "archived-result", replayCapability: null, + } }, { fetcher: async (url) => { + assert.equal(url, "/api/v1/observatory/lab-projections/lab-old"); called = true; + return new Response(null, { status: 204 }); + } }); + assert.equal(called, true); +}); diff --git a/apps/control-station/test/observatoryHooks.test.mjs b/apps/control-station/test/observatoryHooks.test.mjs deleted file mode 100644 index f6032c7c..00000000 --- a/apps/control-station/test/observatoryHooks.test.mjs +++ /dev/null @@ -1,96 +0,0 @@ -import assert from "node:assert/strict"; -import React from "react"; -import { after, before, test } from "node:test"; -import { createServer } from "./support/vite-server.mjs"; - -let server; -let useObservatoryRecordedJobs; -let useObservatoryLaboratorySetups; - -before(async () => { - server = await createServer({ - appType: "custom", logLevel: "silent", server: { middlewareMode: true }, - }); - ({ useObservatoryRecordedJobs } = await server.ssrLoadModule("/src/core/observatory/useObservatoryRecordedJobs.ts")); - ({ useObservatoryLaboratorySetups } = await server.ssrLoadModule("/src/core/observatory/useObservatoryLaboratorySetups.ts")); -}); -after(async () => { await server?.close(); }); - -// Deliberately inspect the render BEFORE effects/cleanup: stale state must already be hidden. -function renderBeforeEffects(hook, args, stateSlots) { - const internals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; - const previous = internals.H; - let stateIndex = 0; - internals.H = { - useState: (initial) => [ - stateIndex < stateSlots.length ? stateSlots[stateIndex++] - : typeof initial === "function" ? initial() : initial, - () => {}, - ], - useRef: (value) => ({ current: value }), - useMemo: (factory) => factory(), - useCallback: (fn) => fn, - useEffect: () => {}, - }; - try { return hook(...args); } finally { internals.H = previous; } -} - -test("queue data and errors cannot survive a source/setup/version change for one render", () => { - const original = ["source-a", "profile-a", "a".repeat(64)]; - const activeJob = { state: "running", publication: { state: "not-required" } }; - const snapshot = { - selectionKey: JSON.stringify(original), jobs: [activeJob], state: "ready", error: "old error", - }; - assert.equal(renderBeforeEffects(useObservatoryRecordedJobs, original, [snapshot]).activeJob, activeJob); - for (const next of [ - ["source-b", original[1], original[2]], - [original[0], "profile-b", original[2]], - [original[0], original[1], "b".repeat(64)], - ["", "", ""], - ]) { - const view = renderBeforeEffects(useObservatoryRecordedJobs, next, [snapshot]); - assert.deepEqual(view.jobs, []); - assert.equal(view.activeJob, null); - assert.equal(view.latestJob, null); - assert.equal(view.error, null); - assert.notEqual(view.state, "ready"); - } -}); - -test("published, incompatible and previous-source profiles have no effective selection", () => { - const profile = { - setupId: "profile-a", origin: "portable-definition", - compatibility: { compatible: true }, - runDefinition: { definitionSha256: "a".repeat(64) }, - preflight: { outcome: "ready" }, - }; - function render(sourceId, setups) { - return renderBeforeEffects(useObservatoryLaboratorySetups, [sourceId], [ - { sourceSessionId: "source-a", setups }, "ready", null, "profile-a", 0, { kind: "idle" }, - ]); - } - assert.equal(render("source-a", [profile]).selectedSetupId, "profile-a"); - for (const view of [ - render("source-b", [profile]), - render("source-a", [{ ...profile, preflight: { outcome: "existing" } }]), - render("source-a", [{ ...profile, compatibility: { compatible: false } }]), - render("source-a", []), - ]) { - assert.equal(view.selectedSetupId, ""); - assert.equal(view.selectedSetup, null); - assert.deepEqual(view.selectableSetups, []); - } -}); - -test("historical failures are not presented as errors of a new operator action", () => { - const selection = ["source-a", "profile-a", "a".repeat(64)]; - const snapshot = { - selectionKey: JSON.stringify(selection), - jobs: [{ jobId: "old-run", state: "failed", publication: { state: "not-required" } }], - state: "ready", error: null, - }; - const view = renderBeforeEffects(useObservatoryRecordedJobs, selection, [snapshot]); - assert.equal(view.computationFailed, false); - assert.equal(view.error, null); - assert.equal(view.activeJob, null); -}); diff --git a/apps/control-station/test/observatoryWorkspace.test.mjs b/apps/control-station/test/observatoryWorkspace.test.mjs index 806995f5..689b863b 100644 --- a/apps/control-station/test/observatoryWorkspace.test.mjs +++ b/apps/control-station/test/observatoryWorkspace.test.mjs @@ -101,7 +101,7 @@ test("Observatory mounts the one shared canonical replay only after explicit adm assert.doesNotMatch(workspace, /evidenceConfigurationLabel\([^)]*,\s*selectedSession\.source\.label/); assert.match( workspace, - /evidence\.recordedRun \? \([\s\S]*name="trash"[\s\S]*name="edit"[\s\S]*Открыть визуальный разбор:[\s\S]*name="eye"/, + /name="trash"[\s\S]*name="edit"[\s\S]*evidence\.recordedRun \? ]*tone="soft"/); assert.match(workspace, /Открыть визуальный разбор/); @@ -200,8 +200,8 @@ test("Observatory rename and delete use admitted projection mutations and canoni assert.match(workspace, /[\s\S]*Сохранить/); - assert.match(workspace, /= 0 && deleteFlowEnd > deleteFlowStart); const wholeDeleteFlow = workspace.slice(deleteFlowStart, deleteFlowEnd); - const evidenceFlowStart = wholeDeleteFlow.indexOf("if (!deleteTarget?.recordedRun"); + const evidenceFlowStart = wholeDeleteFlow.indexOf("if (!deleteTarget ||"); assert.ok(evidenceFlowStart >= 0); const deleteFlow = wholeDeleteFlow.slice(evidenceFlowStart); const teardown = deleteFlow.indexOf("closeReplay();"); @@ -296,7 +296,7 @@ test("Observatory configures independent AI modules and shows queued evidence pr assert.match(workspace, /computing: \[25, 90\]/); assert.match(workspace, /Подготавливаем камеру и LiDAR/); assert.match(workspace, /прошло.*formatDuration\(progress\.elapsedSeconds\)/s); - assert.match(workspace, /Не удалось запустить модель/); + assert.match(workspace, /return failedRunDetail\(job\)/); assert.doesNotMatch(workspace, /job\.terminalMessage|job\.publication\.error/); assert.doesNotMatch(workspace, /function aiModuleLabel\(/); assert.match(workspace, /aiJobsController\.moduleLabelsBySetup\[job\.setupId\] \?\? job\.setupId/); @@ -334,11 +334,9 @@ test("Observatory configures independent AI modules and shows queued evidence pr /accumulationSeconds: showLocalSlam \? sceneDraft\.accumulationSeconds : 0/, ); assert.match(workspace, //); - assert.match(workspace, /function presentAIJob\(job: ObservatoryRecordedJob\)/); - assert.match(workspace, /if \(job\.state === "failed"\) return true/); - assert.match(workspace, /return job\.state !== "succeeded"/); - assert.match(workspace, /function presentLatestAIJobs/); - assert.match(workspace, /seenSetups\.has\(job\.setupId\)/); + assert.doesNotMatch(workspace, /presentLatestAIJobs|seenSetups/); + assert.match(workspace, /evidence.lab.resultId === job.resultId/); + assert.match(workspace, /История запусков/); assert.match(configWindow, /fetchAICompositionJobs\(sourceSessionId, request\.signal\)/); assert.match( configWindow, diff --git a/config/observatory-portable-run-definitions.json b/config/observatory-portable-run-definitions.json index 36ecee49..11f53054 100644 --- a/config/observatory-portable-run-definitions.json +++ b/config/observatory-portable-run-definitions.json @@ -1 +1,570 @@ -{"definitions":[{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"ddrnet-portable-runtime-config-v2","kind":"configuration","sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"component_id":"eomt-recorded-dependency-set-v1","kind":"dependency-set","sha256":"4eb1f8d33236806e74f9e5bb96b7dce2ac37623dc39b2184be2aa8d7d00e983e"},{"component_id":"eomt-recorded-orchestrator-v1","kind":"orchestrator","sha256":"d3e9435939444ab35b27a744ac314e289ebd66a13fa56e3d59f121e088d22774"},{"component_id":"eomt-recorded-profile-v1","kind":"profile","sha256":"ea583966bc3409f5cf563cbf4fad05e366907e67187082eb692aff53d9f5d875"},{"component_id":"eomt-recorded-runner-v1","kind":"runner","sha256":"1e64869de48d10f1531c742e6067c4c3ae2a709c5eb0d770d1fab74b4a2431ff"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"vegetation-mission-policy-v1","kind":"policy","sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"component_id":"vegetation-provider-label-map-v1","kind":"provider-map","sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"definition_id":"lab-v1-eomt-ddrnet-portable","definition_sha256":"269d71a24b4e63cff54e01273f9d4b35fc6cdd72bc6fadec206169ae0777e6ac","executor":{"contour_id":"worker-006","image_sha256":"5ad7d95baac63af13812cb693d492add4e806a333aba8e60edb2ea1aba754373","reason":null,"reason_code":null,"release_id":"lab-v1-installed-package-v1","release_sha256":"667858623962cd6d9849a8985b803f59e429916b5c56f76a6fc6c80c0c54526b","state":"ready"},"models":[{"architecture":"EomtForUniversalSegmentation","artifacts":[{"byte_length":1575,"role":"config-json","sha256":"7f4aa94fa4e43c0dbd79a5420edb511120aef62bd82bfbcbcece79948286a650"},{"byte_length":1276175488,"role":"model-weights","sha256":"c265da9a74f58f5c3f4826d23ca4ca78beac0b106cca5842beca61580de5b782"},{"byte_length":666,"role":"preprocessor-config","sha256":"97e2fbf7f0bdba2cfc90251c5133bae9c27ddc9c4410509f40670be2332854e7"}],"model_id":"tue-mps/cityscapes_semantic_eomt_large_1024","release_id":"eomt-cityscapes-large-1024-v1","revision":"8d6b6d1a3f7b50d441afd7d247c2ed10db186e8f"},{"architecture":"ddrnet_39","artifacts":[{"byte_length":259419077,"role":"checkpoint","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"}],"model_id":"goose-ddrnet-class-512","release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"recorded-eomt-ddrnet-review-v2","contract_sha256":"b3dfaa8e20a0f22fc510d062ac469f010a3281c650059d9ea134f0b3ccb38d9a","publication":"observatory","result_kind":"recorded-perception-qualification","result_schema":"missioncore.recorded-eomt-ddrnet-review/v2","schema_version":"missioncore.observatory-portable-result-contract/v2","version":2},"setup_id":"lab-v1-eomt-ddrnet-portable-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-observatory-v2","contract_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","version":2},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["point-cloud","trajectory","video"],"seekable":true},"version":2},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"m49-tgs-portable-profile-v2","kind":"configuration","sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"component_id":"m49-tgs-portable-runner-v1","kind":"runner","sha256":"e3bb2e91c70712eff74e8e69718075a407e042fb494616d65984500da42b21a9"}],"definition_id":"m49-tgs-portable","definition_sha256":"f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb","executor":{"contour_id":"worker-006","image_sha256":"f9278ab21aa65045be993dd19bffc25f49955e19598893ac78cc4761ca63ecf3","reason":null,"reason_code":null,"release_id":"m49-tgs-portable-executor-v1","release_sha256":"c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa","state":"ready"},"models":[],"resource_profile":{"accelerator_id":"cpu-only","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-cpu-single-run-portable-v2","profile_sha256":"49e373f1cbf314e7fab2d176db295f3d3d9ddbbcbd724bbde988ef60ad767dee","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"m49-tgs-portable-review-v2","contract_sha256":"9dd80c8e2504559d2156fca933de6eb27901e35305e6853aeb84707e1cb13892","publication":"observatory","result_kind":"recorded-perception-qualification","result_schema":"missioncore.recorded-tgs-costmap-review/v2","schema_version":"missioncore.observatory-portable-result-contract/v2","version":2},"setup_id":"m49-tgs-portable-v2","source_adapter":{"adapter_id":"xgrids-k1-recorded-observatory-v2","contract_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","version":2},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["point-cloud","trajectory","video"],"seekable":true},"version":3},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"ddrnet-portable-runtime-config-v2","kind":"configuration","sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"component_id":"ddrnet-recorded-profile-v1","kind":"profile","sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"component_id":"ddrnet-recorded-runner-v1","kind":"runner","sha256":"b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"vegetation-mission-policy-v1","kind":"policy","sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"component_id":"vegetation-provider-label-map-v1","kind":"provider-map","sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"definition_id":"ai-segmentation-ddrnet","definition_sha256":"04dd11b9bca4956bc253c970a9020a5fac80e9ef5981ff1fffc32b9646087fec","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"ddrnet_39","artifacts":[{"byte_length":259419077,"role":"checkpoint","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"}],"model_id":"goose-ddrnet-class-512","release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-segmentation-ddrnet-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-ai-layer-v1","contract_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","version":1},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["video"],"seekable":true},"version":1},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"eomt-recorded-dependency-set-v1","kind":"dependency-set","sha256":"4eb1f8d33236806e74f9e5bb96b7dce2ac37623dc39b2184be2aa8d7d00e983e"},{"component_id":"eomt-recorded-orchestrator-v1","kind":"orchestrator","sha256":"d3e9435939444ab35b27a744ac314e289ebd66a13fa56e3d59f121e088d22774"},{"component_id":"eomt-recorded-profile-v1","kind":"profile","sha256":"ea583966bc3409f5cf563cbf4fad05e366907e67187082eb692aff53d9f5d875"},{"component_id":"eomt-recorded-runner-v1","kind":"runner","sha256":"1e64869de48d10f1531c742e6067c4c3ae2a709c5eb0d770d1fab74b4a2431ff"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"}],"definition_id":"ai-segmentation-eomt","definition_sha256":"387f42bdf707b0e3e357fec1cfb5aa90a64133ebf0095f9b01d749ca2364d47c","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"EomtForUniversalSegmentation","artifacts":[{"byte_length":1575,"role":"config-json","sha256":"7f4aa94fa4e43c0dbd79a5420edb511120aef62bd82bfbcbcece79948286a650"},{"byte_length":1276175488,"role":"model-weights","sha256":"c265da9a74f58f5c3f4826d23ca4ca78beac0b106cca5842beca61580de5b782"},{"byte_length":666,"role":"preprocessor-config","sha256":"97e2fbf7f0bdba2cfc90251c5133bae9c27ddc9c4410509f40670be2332854e7"}],"model_id":"tue-mps/cityscapes_semantic_eomt_large_1024","release_id":"eomt-cityscapes-large-1024-v1","revision":"8d6b6d1a3f7b50d441afd7d247c2ed10db186e8f"}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-segmentation-eomt-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-ai-layer-v1","contract_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","version":1},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["video"],"seekable":true},"version":1},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"rf-detr-recorded-profile-v1","kind":"profile","sha256":"4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0"},{"component_id":"rf-detr-recorded-runner-v1","kind":"runner","sha256":"4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0"}],"definition_id":"ai-detection-rf-detr","definition_sha256":"598ce44f087c392ee95a024c3c45c95bdd02ad8530a3ccbac13422c2ad2f4a94","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"RF-DETR-Large-TensorRT","artifacts":[{"byte_length":68316388,"role":"tensorrt-engine","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"}],"model_id":"rf-detr/large-native-kb4","release_id":"rf-detr-large-native-kb4-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-detection-rf-detr-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-ai-layer-v1","contract_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","version":1},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["video"],"seekable":true},"version":1},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"m49-tgs-portable-profile-v2","kind":"configuration","sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"component_id":"object-distance-recorded-profile-v1","kind":"profile","sha256":"0e3e426e2f768bc019a3715a50fc77a88626869abd9fa919e1aef5763d0c53da"},{"component_id":"object-distance-recorded-runner-v1","kind":"runner","sha256":"0e3e426e2f768bc019a3715a50fc77a88626869abd9fa919e1aef5763d0c53da"},{"component_id":"rf-detr-recorded-dependency-v1","kind":"dependency-set","sha256":"4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0"}],"definition_id":"ai-range-object-distance","definition_sha256":"af5e637b78c670930b60cd4527b611aba4af601e6da58aa4dc8326ea6e13c5c2","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"RF-DETR-Large-TensorRT","artifacts":[{"byte_length":68316388,"role":"tensorrt-engine","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"}],"model_id":"rf-detr/large-native-kb4","release_id":"rf-detr-large-native-kb4-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-object-distance-v1","profile_sha256":"c244efed459915508044fed4ef0e73c810fbe750e5e379d06723f734bd4385ca","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-range-object-distance-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-observatory-v2","contract_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","version":2},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["point-cloud","trajectory","video"],"seekable":true},"version":1}],"schema_version":"missioncore.observatory-portable-run-definition-registry/v2"} \ No newline at end of file +{ + "definitions": [ + { + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "components": [ + { + "component_id": "k1-camera-1-calibration-v1", + "kind": "calibration", + "sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9" + }, + { + "component_id": "m49-tgs-portable-profile-v2", + "kind": "configuration", + "sha256": "6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9" + }, + { + "component_id": "m49-tgs-portable-runner-v1", + "kind": "runner", + "sha256": "e3bb2e91c70712eff74e8e69718075a407e042fb494616d65984500da42b21a9" + } + ], + "definition_id": "m49-tgs-portable", + "definition_sha256": "f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb", + "executor": { + "contour_id": "worker-006", + "image_sha256": "f9278ab21aa65045be993dd19bffc25f49955e19598893ac78cc4761ca63ecf3", + "reason": null, + "reason_code": null, + "release_id": "m49-tgs-portable-executor-v1", + "release_sha256": "c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa", + "state": "ready" + }, + "models": [], + "resource_profile": { + "accelerator_id": "cpu-only", + "allowed_checkpoints": [], + "checkpoint_policy": "non-checkpointable", + "concurrency": 1, + "contour_id": "worker-006", + "profile_id": "worker006-cpu-single-run-portable-v2", + "profile_sha256": "49e373f1cbf314e7fab2d176db295f3d3d9ddbbcbd724bbde988ef60ad767dee", + "schema_version": "missioncore.observatory-portable-resource-profile/v2" + }, + "result_contract": { + "contract_id": "m49-tgs-portable-review-v2", + "contract_sha256": "9dd80c8e2504559d2156fca933de6eb27901e35305e6853aeb84707e1cb13892", + "publication": "observatory", + "result_kind": "recorded-perception-qualification", + "result_schema": "missioncore.recorded-tgs-costmap-review/v2", + "schema_version": "missioncore.observatory-portable-result-contract/v2", + "version": 2 + }, + "setup_id": "m49-tgs-portable-v2", + "source_adapter": { + "adapter_id": "xgrids-k1-recorded-observatory-v2", + "contract_sha256": "4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de", + "version": 2 + }, + "source_requirements": { + "archive_id": "xgrids-k1.viewer-live.evidence", + "calibration_identity_sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9", + "calibration_slot": "camera_1", + "camera_height": 600, + "camera_semantic_channel_id": "camera.video.recorded", + "camera_source_id": "sensor.camera.right", + "camera_width": 800, + "exactly_one_media_epoch": true, + "plugin_id": "nodedc.device.xgrids-lixelkity-k1", + "recorded_media_init_sha256": "e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38", + "recorded_media_type": "video/mp4; codecs=\"avc1.641028\"", + "required_modalities": [ + "point-cloud", + "trajectory", + "video" + ], + "seekable": true + }, + "version": 3 + }, + { + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "components": [ + { + "component_id": "camera-source-recorded-v1", + "kind": "orchestrator", + "sha256": "87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5" + }, + { + "component_id": "ddrnet-portable-runtime-config-v2", + "kind": "configuration", + "sha256": "c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21" + }, + { + "component_id": "ddrnet-recorded-profile-v1", + "kind": "profile", + "sha256": "c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21" + }, + { + "component_id": "ddrnet-recorded-runner-v1", + "kind": "runner", + "sha256": "b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1" + }, + { + "component_id": "k1-camera-1-calibration-v1", + "kind": "calibration", + "sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9" + }, + { + "component_id": "k1-valid-fov-identity-v1", + "kind": "valid-fov-identity", + "sha256": "b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2" + }, + { + "component_id": "k1-valid-fov-mask-v1", + "kind": "valid-fov-mask", + "sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63" + }, + { + "component_id": "vegetation-mission-policy-v1", + "kind": "policy", + "sha256": "b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35" + }, + { + "component_id": "vegetation-provider-label-map-v1", + "kind": "provider-map", + "sha256": "f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352" + } + ], + "definition_id": "ai-segmentation-ddrnet", + "definition_sha256": "04dd11b9bca4956bc253c970a9020a5fac80e9ef5981ff1fffc32b9646087fec", + "executor": { + "contour_id": "worker-006", + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "reason": null, + "reason_code": null, + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721", + "state": "ready" + }, + "models": [ + { + "architecture": "ddrnet_39", + "artifacts": [ + { + "byte_length": 259419077, + "role": "checkpoint", + "sha256": "b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6" + } + ], + "model_id": "goose-ddrnet-class-512", + "release_id": "lab-v1-ddrnet-39-goose-fine-64-v1", + "revision": null + } + ], + "resource_profile": { + "accelerator_id": "nvidia-rtx-4090", + "allowed_checkpoints": [], + "checkpoint_policy": "non-checkpointable", + "concurrency": 1, + "contour_id": "worker-006", + "profile_id": "worker006-single-gpu-sequential-ai-v1", + "profile_sha256": "7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d", + "schema_version": "missioncore.observatory-portable-resource-profile/v2" + }, + "result_contract": { + "contract_id": "ai-layer-result", + "contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "publication": "observatory", + "result_kind": "recorded-ai-layer-review", + "result_schema": "missioncore.recorded-ai-layer-review/v1", + "schema_version": "missioncore.observatory-portable-result-contract/v2", + "version": 1 + }, + "setup_id": "ai-segmentation-ddrnet-v1", + "source_adapter": { + "adapter_id": "xgrids-k1-recorded-ai-layer-v1", + "contract_sha256": "2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e", + "version": 1 + }, + "source_requirements": { + "archive_id": "xgrids-k1.viewer-live.evidence", + "calibration_identity_sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9", + "calibration_slot": "camera_1", + "camera_height": 600, + "camera_semantic_channel_id": "camera.video.recorded", + "camera_source_id": "sensor.camera.right", + "camera_width": 800, + "exactly_one_media_epoch": true, + "plugin_id": "nodedc.device.xgrids-lixelkity-k1", + "recorded_media_init_sha256": "e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38", + "recorded_media_type": "video/mp4; codecs=\"avc1.641028\"", + "required_modalities": [ + "video" + ], + "seekable": true + }, + "version": 1 + }, + { + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "components": [ + { + "component_id": "camera-source-recorded-v1", + "kind": "orchestrator", + "sha256": "87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5" + }, + { + "component_id": "eomt-recorded-dependency-set-v1", + "kind": "dependency-set", + "sha256": "4eb1f8d33236806e74f9e5bb96b7dce2ac37623dc39b2184be2aa8d7d00e983e" + }, + { + "component_id": "eomt-recorded-orchestrator-v1", + "kind": "orchestrator", + "sha256": "d3e9435939444ab35b27a744ac314e289ebd66a13fa56e3d59f121e088d22774" + }, + { + "component_id": "eomt-recorded-profile-v1", + "kind": "profile", + "sha256": "ea583966bc3409f5cf563cbf4fad05e366907e67187082eb692aff53d9f5d875" + }, + { + "component_id": "eomt-recorded-runner-v1", + "kind": "runner", + "sha256": "1e64869de48d10f1531c742e6067c4c3ae2a709c5eb0d770d1fab74b4a2431ff" + }, + { + "component_id": "k1-camera-1-calibration-v1", + "kind": "calibration", + "sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9" + }, + { + "component_id": "k1-valid-fov-identity-v1", + "kind": "valid-fov-identity", + "sha256": "b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2" + }, + { + "component_id": "k1-valid-fov-mask-v1", + "kind": "valid-fov-mask", + "sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63" + } + ], + "definition_id": "ai-segmentation-eomt", + "definition_sha256": "387f42bdf707b0e3e357fec1cfb5aa90a64133ebf0095f9b01d749ca2364d47c", + "executor": { + "contour_id": "worker-006", + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "reason": null, + "reason_code": null, + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721", + "state": "ready" + }, + "models": [ + { + "architecture": "EomtForUniversalSegmentation", + "artifacts": [ + { + "byte_length": 1575, + "role": "config-json", + "sha256": "7f4aa94fa4e43c0dbd79a5420edb511120aef62bd82bfbcbcece79948286a650" + }, + { + "byte_length": 1276175488, + "role": "model-weights", + "sha256": "c265da9a74f58f5c3f4826d23ca4ca78beac0b106cca5842beca61580de5b782" + }, + { + "byte_length": 666, + "role": "preprocessor-config", + "sha256": "97e2fbf7f0bdba2cfc90251c5133bae9c27ddc9c4410509f40670be2332854e7" + } + ], + "model_id": "tue-mps/cityscapes_semantic_eomt_large_1024", + "release_id": "eomt-cityscapes-large-1024-v1", + "revision": "8d6b6d1a3f7b50d441afd7d247c2ed10db186e8f" + } + ], + "resource_profile": { + "accelerator_id": "nvidia-rtx-4090", + "allowed_checkpoints": [], + "checkpoint_policy": "non-checkpointable", + "concurrency": 1, + "contour_id": "worker-006", + "profile_id": "worker006-single-gpu-sequential-ai-v1", + "profile_sha256": "7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d", + "schema_version": "missioncore.observatory-portable-resource-profile/v2" + }, + "result_contract": { + "contract_id": "ai-layer-result", + "contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "publication": "observatory", + "result_kind": "recorded-ai-layer-review", + "result_schema": "missioncore.recorded-ai-layer-review/v1", + "schema_version": "missioncore.observatory-portable-result-contract/v2", + "version": 1 + }, + "setup_id": "ai-segmentation-eomt-v1", + "source_adapter": { + "adapter_id": "xgrids-k1-recorded-ai-layer-v1", + "contract_sha256": "2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e", + "version": 1 + }, + "source_requirements": { + "archive_id": "xgrids-k1.viewer-live.evidence", + "calibration_identity_sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9", + "calibration_slot": "camera_1", + "camera_height": 600, + "camera_semantic_channel_id": "camera.video.recorded", + "camera_source_id": "sensor.camera.right", + "camera_width": 800, + "exactly_one_media_epoch": true, + "plugin_id": "nodedc.device.xgrids-lixelkity-k1", + "recorded_media_init_sha256": "e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38", + "recorded_media_type": "video/mp4; codecs=\"avc1.641028\"", + "required_modalities": [ + "video" + ], + "seekable": true + }, + "version": 1 + }, + { + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "components": [ + { + "component_id": "camera-source-recorded-v1", + "kind": "orchestrator", + "sha256": "87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5" + }, + { + "component_id": "k1-camera-1-calibration-v1", + "kind": "calibration", + "sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9" + }, + { + "component_id": "k1-valid-fov-identity-v1", + "kind": "valid-fov-identity", + "sha256": "b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2" + }, + { + "component_id": "k1-valid-fov-mask-v1", + "kind": "valid-fov-mask", + "sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63" + }, + { + "component_id": "rf-detr-recorded-profile-v1", + "kind": "profile", + "sha256": "4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0" + }, + { + "component_id": "rf-detr-recorded-runner-v1", + "kind": "runner", + "sha256": "4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0" + } + ], + "definition_id": "ai-detection-rf-detr", + "definition_sha256": "598ce44f087c392ee95a024c3c45c95bdd02ad8530a3ccbac13422c2ad2f4a94", + "executor": { + "contour_id": "worker-006", + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "reason": null, + "reason_code": null, + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721", + "state": "ready" + }, + "models": [ + { + "architecture": "RF-DETR-Large-TensorRT", + "artifacts": [ + { + "byte_length": 68316388, + "role": "tensorrt-engine", + "sha256": "b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695" + } + ], + "model_id": "rf-detr/large-native-kb4", + "release_id": "rf-detr-large-native-kb4-v1", + "revision": null + } + ], + "resource_profile": { + "accelerator_id": "nvidia-rtx-4090", + "allowed_checkpoints": [], + "checkpoint_policy": "non-checkpointable", + "concurrency": 1, + "contour_id": "worker-006", + "profile_id": "worker006-single-gpu-sequential-ai-v1", + "profile_sha256": "7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d", + "schema_version": "missioncore.observatory-portable-resource-profile/v2" + }, + "result_contract": { + "contract_id": "ai-layer-result", + "contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "publication": "observatory", + "result_kind": "recorded-ai-layer-review", + "result_schema": "missioncore.recorded-ai-layer-review/v1", + "schema_version": "missioncore.observatory-portable-result-contract/v2", + "version": 1 + }, + "setup_id": "ai-detection-rf-detr-v1", + "source_adapter": { + "adapter_id": "xgrids-k1-recorded-ai-layer-v1", + "contract_sha256": "2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e", + "version": 1 + }, + "source_requirements": { + "archive_id": "xgrids-k1.viewer-live.evidence", + "calibration_identity_sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9", + "calibration_slot": "camera_1", + "camera_height": 600, + "camera_semantic_channel_id": "camera.video.recorded", + "camera_source_id": "sensor.camera.right", + "camera_width": 800, + "exactly_one_media_epoch": true, + "plugin_id": "nodedc.device.xgrids-lixelkity-k1", + "recorded_media_init_sha256": "e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38", + "recorded_media_type": "video/mp4; codecs=\"avc1.641028\"", + "required_modalities": [ + "video" + ], + "seekable": true + }, + "version": 1 + }, + { + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "components": [ + { + "component_id": "camera-source-recorded-v1", + "kind": "orchestrator", + "sha256": "87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5" + }, + { + "component_id": "k1-camera-1-calibration-v1", + "kind": "calibration", + "sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9" + }, + { + "component_id": "k1-valid-fov-identity-v1", + "kind": "valid-fov-identity", + "sha256": "b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2" + }, + { + "component_id": "k1-valid-fov-mask-v1", + "kind": "valid-fov-mask", + "sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63" + }, + { + "component_id": "m49-tgs-portable-profile-v2", + "kind": "configuration", + "sha256": "6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9" + }, + { + "component_id": "object-distance-recorded-profile-v1", + "kind": "profile", + "sha256": "0e3e426e2f768bc019a3715a50fc77a88626869abd9fa919e1aef5763d0c53da" + }, + { + "component_id": "object-distance-recorded-runner-v1", + "kind": "runner", + "sha256": "0e3e426e2f768bc019a3715a50fc77a88626869abd9fa919e1aef5763d0c53da" + }, + { + "component_id": "rf-detr-recorded-dependency-v1", + "kind": "dependency-set", + "sha256": "4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0" + } + ], + "definition_id": "ai-range-object-distance", + "definition_sha256": "af5e637b78c670930b60cd4527b611aba4af601e6da58aa4dc8326ea6e13c5c2", + "executor": { + "contour_id": "worker-006", + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "reason": null, + "reason_code": null, + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721", + "state": "ready" + }, + "models": [ + { + "architecture": "RF-DETR-Large-TensorRT", + "artifacts": [ + { + "byte_length": 68316388, + "role": "tensorrt-engine", + "sha256": "b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695" + } + ], + "model_id": "rf-detr/large-native-kb4", + "release_id": "rf-detr-large-native-kb4-v1", + "revision": null + } + ], + "resource_profile": { + "accelerator_id": "nvidia-rtx-4090", + "allowed_checkpoints": [], + "checkpoint_policy": "non-checkpointable", + "concurrency": 1, + "contour_id": "worker-006", + "profile_id": "worker006-single-gpu-sequential-ai-object-distance-v1", + "profile_sha256": "c244efed459915508044fed4ef0e73c810fbe750e5e379d06723f734bd4385ca", + "schema_version": "missioncore.observatory-portable-resource-profile/v2" + }, + "result_contract": { + "contract_id": "ai-layer-result", + "contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "publication": "observatory", + "result_kind": "recorded-ai-layer-review", + "result_schema": "missioncore.recorded-ai-layer-review/v1", + "schema_version": "missioncore.observatory-portable-result-contract/v2", + "version": 1 + }, + "setup_id": "ai-range-object-distance-v1", + "source_adapter": { + "adapter_id": "xgrids-k1-recorded-observatory-v2", + "contract_sha256": "4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de", + "version": 2 + }, + "source_requirements": { + "archive_id": "xgrids-k1.viewer-live.evidence", + "calibration_identity_sha256": "05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9", + "calibration_slot": "camera_1", + "camera_height": 600, + "camera_semantic_channel_id": "camera.video.recorded", + "camera_source_id": "sensor.camera.right", + "camera_width": 800, + "exactly_one_media_epoch": true, + "plugin_id": "nodedc.device.xgrids-lixelkity-k1", + "recorded_media_init_sha256": "e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38", + "recorded_media_type": "video/mp4; codecs=\"avc1.641028\"", + "required_modalities": [ + "point-cloud", + "trajectory", + "video" + ], + "seekable": true + }, + "version": 1 + } + ], + "schema_version": "missioncore.observatory-portable-run-definition-registry/v2" +} diff --git a/config/observatory-worker-runtime-candidates.json b/config/observatory-worker-runtime-candidates.json index f525ecf4..a64ddd98 100644 --- a/config/observatory-worker-runtime-candidates.json +++ b/config/observatory-worker-runtime-candidates.json @@ -1 +1,684 @@ -{"candidates":[{"adapter_id":"lab-v1-installed-package-worker006-v1","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"0b6958e3a1b4e12e04619f447ca9ce915021aa1aaa6034ea6bc309c26efbd060","definition_id":"lab-v1-eomt-ddrnet-portable","definition_sha256":"269d71a24b4e63cff54e01273f9d4b35fc6cdd72bc6fadec206169ae0777e6ac","definition_version":2,"executor":{"image_sha256":"5ad7d95baac63af13812cb693d492add4e806a333aba8e60edb2ea1aba754373","release_id":"lab-v1-installed-package-v1","release_sha256":"667858623962cd6d9849a8985b803f59e429916b5c56f76a6fc6c80c0c54526b"},"model_manifest_sha256":"3fd2d43af73bd73f89d9ffae95d8770cfdeb46033ec967509124fac6ae4afe56","phases":[{"phase_id":"source-delivery","state":"implemented"},{"phase_id":"prepare-source","state":"implemented"},{"phase_id":"eomt-step","state":"implemented"},{"phase_id":"ddrnet-step","state":"implemented"},{"phase_id":"assemble-result","state":"implemented"},{"phase_id":"result-publication","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"b3dfaa8e20a0f22fc510d062ac469f010a3281c650059d9ea134f0b3ccb38d9a","reusable_assets":[{"asset_id":"agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"5ad7d95baac63af13812cb693d492add4e806a333aba8e60edb2ea1aba754373"},{"asset_id":"ddrnet-checkpoint","byte_length":259419077,"component_id":null,"kind":"model-artifact","model_artifact_role":"checkpoint","model_release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"},{"asset_id":"ddrnet-goose-mapping","byte_length":1427,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f"},{"asset_id":"ddrnet-goose-runner","byte_length":32877,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1"},{"asset_id":"ddrnet-portable-config","byte_length":4324,"component_id":"ddrnet-portable-runtime-config-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"asset_id":"ddrnet-step-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"e6c986100613ec804f0e0076ca8695abf43ff88ef9d5d85f6857e0b41db74051"},{"asset_id":"eomt-environment","byte_length":211776082,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"eomt-model-cache","byte_length":2552355458,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c"},{"asset_id":"eomt-python-environment","byte_length":5120848705,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20"},{"asset_id":"eomt-runner-bundle","byte_length":145141,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7"},{"asset_id":"eomt-step-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"adba3dc8c97b161ba261ec44fca9ebe1680f117d1bcb1481440172cc3331a174"},{"asset_id":"eomt-transformers-environment","byte_length":225272284,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9"},{"asset_id":"k1-valid-fov-root","byte_length":6019,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e"},{"asset_id":"lab-v1-definition-registry","byte_length":7177,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"1de9a07153fa6f51088aecdbcf74d12c9e58716c5feb0145d6e54f20a8c300cb"},{"asset_id":"lab-v1-package-contract","byte_length":3531,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"c7a576aba09ccb0a343ad46ad90f1dab589ed51353d575026a508f8d6fa8dcc4"},{"asset_id":"vegetation-policy","byte_length":3022,"component_id":"vegetation-mission-policy-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"asset_id":"vegetation-provider-map","byte_length":2756,"component_id":"vegetation-provider-label-map-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"lab-v1-eomt-ddrnet-portable-v1","source_adapter_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","state":"ready"},{"adapter_id":"m49-tgs-worker006-portable-v2","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"65cd2063146a1dd320e30d5f4e21e4bf0aab1ff683e846926cbbfbe25a9f8a5e","definition_id":"m49-tgs-portable","definition_sha256":"f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb","definition_version":3,"executor":{"image_sha256":"f9278ab21aa65045be993dd19bffc25f49955e19598893ac78cc4761ca63ecf3","release_id":"m49-tgs-portable-executor-v1","release_sha256":"c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa"},"model_manifest_sha256":"489a43448f720a9b5c7993dc8279d167b77191a586f0d87b6d38b81cf728e2f1","phases":[{"phase_id":"source-delivery","state":"implemented"},{"phase_id":"camera-lidar-timeline-materializer","state":"implemented"},{"phase_id":"portable-tgs-input-materializer","state":"implemented"},{"phase_id":"portable-tgs-runner","state":"implemented"},{"phase_id":"result-v2-assembler","state":"implemented"},{"phase_id":"observatory-result-publisher","state":"implemented"}],"resource_profile_sha256":"49e373f1cbf314e7fab2d176db295f3d3d9ddbbcbd724bbde988ef60ad767dee","result_contract_sha256":"9dd80c8e2504559d2156fca933de6eb27901e35305e6853aeb84707e1cb13892","reusable_assets":[{"asset_id":"m49-portable-compiled-runner","byte_length":274168,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"7be449392ef161fb8713b4c984705d2373bc3cd05645332d92b88a8bff0c7db3"},{"asset_id":"m49-portable-compiled-runner-build-seal","byte_length":1014,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"e3bb2e91c70712eff74e8e69718075a407e042fb494616d65984500da42b21a9"},{"asset_id":"m49-portable-executor-release","byte_length":1693,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa"},{"asset_id":"m49-portable-profile","byte_length":1683,"component_id":"m49-tgs-portable-profile-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"asset_id":"m49-portable-worker-installation-receipt","byte_length":2672,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"b560ff9e02746cbb760502f2a3b4b7bd564f95ab52d1149d189927a326b1645a"},{"asset_id":"travel-tgs-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7b412020f4d8392d1d1ed1b33beadc44140f0ea8f781e62dd69796042334300f"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"m49-tgs-portable-v2","source_adapter_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-ddrnet","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"66dd1b086b03799b08adde8c64461c7b8e09b183bb9e14f169933e625dcbc070","definition_id":"ai-segmentation-ddrnet","definition_sha256":"04dd11b9bca4956bc253c970a9020a5fac80e9ef5981ff1fffc32b9646087fec","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"c9144b30d054e3d495961486a4aed70ae5f60bcadadb4e3309865ced4123739e","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"ddrnet-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-ddrnet-profile","byte_length":4324,"component_id":"ddrnet-portable-runtime-config-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"ddrnet-checkpoint","byte_length":259419077,"component_id":null,"kind":"model-artifact","model_artifact_role":"checkpoint","model_release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"},{"asset_id":"ddrnet-goose-mapping","byte_length":1427,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f"},{"asset_id":"ddrnet-goose-runner","byte_length":32877,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1"},{"asset_id":"ddrnet-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"a3b7d22f5d3bfdf2d84444b936c8b01abf8243be652387d7e2024ba7bda587f5"},{"asset_id":"ddrnet-package-contract","byte_length":2307,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"34768724991372beee8a3e21baca66e5467671c2639ec699a55eecf2dc8268b9"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"vegetation-policy","byte_length":3022,"component_id":"vegetation-mission-policy-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"asset_id":"vegetation-provider-map","byte_length":2756,"component_id":"vegetation-provider-label-map-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-segmentation-ddrnet-v1","source_adapter_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-eomt","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"b6c7d84a051bd9c5a163f74cb78bd6aa7a96b6c34e3f5cdfc2f99d4aeca8df7b","definition_id":"ai-segmentation-eomt","definition_sha256":"387f42bdf707b0e3e357fec1cfb5aa90a64133ebf0095f9b01d749ca2364d47c","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"94dc40430c2ac23d45aaf14dd26f85f2ca9ba0ec975fe4b08e585c32dd79a223","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"eomt-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"eomt-environment","byte_length":211776082,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"eomt-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"211852dfae4ab1acbd1195d4968a385ea56bd7bd3d0c4241a6be7e02794999b7"},{"asset_id":"eomt-model-cache","byte_length":2552355458,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c"},{"asset_id":"eomt-package-contract","byte_length":2649,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"3863c4a3f8328221acf66e70dd0cb66c71b0c93b25ef050c072ba351f3edfa5d"},{"asset_id":"eomt-python-environment","byte_length":5120848705,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20"},{"asset_id":"eomt-runner-bundle","byte_length":145141,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7"},{"asset_id":"eomt-transformers-environment","byte_length":225272284,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9"},{"asset_id":"k1-valid-fov-root","byte_length":6019,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-segmentation-eomt-v1","source_adapter_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-rf-detr","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"aae136d27d4c013dec111d2b83c22f55df8dcd0dd73a2be5ed47b67f490164f4","definition_id":"ai-detection-rf-detr","definition_sha256":"598ce44f087c392ee95a024c3c45c95bdd02ad8530a3ccbac13422c2ad2f4a94","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"edef8446597b801f67538e9e1f056cbb55e56bf61ca4127efd97ce98e7473788","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"rf-detr-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"rf-detr-engine","byte_length":68316388,"component_id":null,"kind":"model-artifact","model_artifact_role":"tensorrt-engine","model_release_id":"rf-detr-large-native-kb4-v1","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"},{"asset_id":"rf-detr-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"57e5e9bc3033f3dfa696a9135928b8260702a77aadfcaee97a2eb9ccd28d7b48"},{"asset_id":"rf-detr-package-contract","byte_length":1702,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"00291bebb09af4d615b7670f0f4e5084cd5665d46238a6bb5ff93a76ff95cc18"},{"asset_id":"rf-detr-valid-fov","byte_length":3668,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-detection-rf-detr-v1","source_adapter_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-object-distance","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"ec35befdde1a23fb62eda0de582420cd858c9cc7ad46a82f1cf05f07ce2fe39e","definition_id":"ai-range-object-distance","definition_sha256":"af5e637b78c670930b60cd4527b611aba4af601e6da58aa4dc8326ea6e13c5c2","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"edef8446597b801f67538e9e1f056cbb55e56bf61ca4127efd97ce98e7473788","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"object-distance-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"c244efed459915508044fed4ef0e73c810fbe750e5e379d06723f734bd4385ca","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"ai-module-m49-profile","byte_length":1683,"component_id":"m49-tgs-portable-profile-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"k1-camera-lidar-calibration","byte_length":72996000,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"0685d24219d8236caf8b7f1685e93f6d6b59e7fd015a768d88a92bbe8b154944"},{"asset_id":"object-distance-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"03908003f7531f677fae50ffad12019c6a62ada773f7e84431bfb9c35982c081"},{"asset_id":"object-distance-package-contract","byte_length":2096,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"7e019064c94884f670d2babecdbd69c6d45082d709ef4cdc6421e3498d1c2c69"},{"asset_id":"rf-detr-engine","byte_length":68316388,"component_id":null,"kind":"model-artifact","model_artifact_role":"tensorrt-engine","model_release_id":"rf-detr-large-native-kb4-v1","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"},{"asset_id":"rf-detr-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"57e5e9bc3033f3dfa696a9135928b8260702a77aadfcaee97a2eb9ccd28d7b48"},{"asset_id":"rf-detr-valid-fov","byte_length":3668,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-range-object-distance-v1","source_adapter_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","state":"ready"}],"schema_version":"missioncore.observatory-portable-worker-runtime-registry/v1"} \ No newline at end of file +{ + "candidates": [ + { + "adapter_id": "m49-tgs-worker006-portable-v2", + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "blockers": [], + "candidate_sha256": "65cd2063146a1dd320e30d5f4e21e4bf0aab1ff683e846926cbbfbe25a9f8a5e", + "definition_id": "m49-tgs-portable", + "definition_sha256": "f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb", + "definition_version": 3, + "executor": { + "image_sha256": "f9278ab21aa65045be993dd19bffc25f49955e19598893ac78cc4761ca63ecf3", + "release_id": "m49-tgs-portable-executor-v1", + "release_sha256": "c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa" + }, + "model_manifest_sha256": "489a43448f720a9b5c7993dc8279d167b77191a586f0d87b6d38b81cf728e2f1", + "phases": [ + { + "phase_id": "source-delivery", + "state": "implemented" + }, + { + "phase_id": "camera-lidar-timeline-materializer", + "state": "implemented" + }, + { + "phase_id": "portable-tgs-input-materializer", + "state": "implemented" + }, + { + "phase_id": "portable-tgs-runner", + "state": "implemented" + }, + { + "phase_id": "result-v2-assembler", + "state": "implemented" + }, + { + "phase_id": "observatory-result-publisher", + "state": "implemented" + } + ], + "resource_profile_sha256": "49e373f1cbf314e7fab2d176db295f3d3d9ddbbcbd724bbde988ef60ad767dee", + "result_contract_sha256": "9dd80c8e2504559d2156fca933de6eb27901e35305e6853aeb84707e1cb13892", + "reusable_assets": [ + { + "asset_id": "m49-portable-compiled-runner", + "byte_length": 274168, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "7be449392ef161fb8713b4c984705d2373bc3cd05645332d92b88a8bff0c7db3" + }, + { + "asset_id": "m49-portable-compiled-runner-build-seal", + "byte_length": 1014, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "e3bb2e91c70712eff74e8e69718075a407e042fb494616d65984500da42b21a9" + }, + { + "asset_id": "m49-portable-executor-release", + "byte_length": 1693, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa" + }, + { + "asset_id": "m49-portable-profile", + "byte_length": 1683, + "component_id": "m49-tgs-portable-profile-v2", + "kind": "definition-component", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9" + }, + { + "asset_id": "m49-portable-worker-installation-receipt", + "byte_length": 2672, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "b560ff9e02746cbb760502f2a3b4b7bd564f95ab52d1149d189927a326b1645a" + }, + { + "asset_id": "travel-tgs-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "7b412020f4d8392d1d1ed1b33beadc44140f0ea8f781e62dd69796042334300f" + } + ], + "schema_version": "missioncore.observatory-portable-worker-runtime-candidate/v1", + "setup_id": "m49-tgs-portable-v2", + "source_adapter_sha256": "4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de", + "state": "ready" + }, + { + "adapter_id": "ai-modular-package-worker006-v1-ddrnet", + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "blockers": [], + "candidate_sha256": "66dd1b086b03799b08adde8c64461c7b8e09b183bb9e14f169933e625dcbc070", + "definition_id": "ai-segmentation-ddrnet", + "definition_sha256": "04dd11b9bca4956bc253c970a9020a5fac80e9ef5981ff1fffc32b9646087fec", + "definition_version": 1, + "executor": { + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721" + }, + "model_manifest_sha256": "c9144b30d054e3d495961486a4aed70ae5f60bcadadb4e3309865ced4123739e", + "phases": [ + { + "phase_id": "source-materialization", + "state": "implemented" + }, + { + "phase_id": "camera-source", + "state": "implemented" + }, + { + "phase_id": "ddrnet-inference", + "state": "implemented" + }, + { + "phase_id": "result-assembly", + "state": "implemented" + } + ], + "resource_profile_sha256": "7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d", + "result_contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "reusable_assets": [ + { + "asset_id": "ai-module-agent-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab" + }, + { + "asset_id": "ai-module-ddrnet-profile", + "byte_length": 4324, + "component_id": "ddrnet-portable-runtime-config-v2", + "kind": "definition-component", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21" + }, + { + "asset_id": "ai-module-definition-registry", + "byte_length": 21610, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30" + }, + { + "asset_id": "camera-source-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561" + }, + { + "asset_id": "ddrnet-checkpoint", + "byte_length": 259419077, + "component_id": null, + "kind": "model-artifact", + "model_artifact_role": "checkpoint", + "model_release_id": "lab-v1-ddrnet-39-goose-fine-64-v1", + "sha256": "b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6" + }, + { + "asset_id": "ddrnet-goose-mapping", + "byte_length": 1427, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f" + }, + { + "asset_id": "ddrnet-goose-runner", + "byte_length": 32877, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1" + }, + { + "asset_id": "ddrnet-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "a3b7d22f5d3bfdf2d84444b936c8b01abf8243be652387d7e2024ba7bda587f5" + }, + { + "asset_id": "ddrnet-package-contract", + "byte_length": 2307, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "34768724991372beee8a3e21baca66e5467671c2639ec699a55eecf2dc8268b9" + }, + { + "asset_id": "eomt-ffmpeg-runtime", + "byte_length": 256208352, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69" + }, + { + "asset_id": "vegetation-policy", + "byte_length": 3022, + "component_id": "vegetation-mission-policy-v1", + "kind": "definition-component", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35" + }, + { + "asset_id": "vegetation-provider-map", + "byte_length": 2756, + "component_id": "vegetation-provider-label-map-v1", + "kind": "definition-component", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352" + } + ], + "schema_version": "missioncore.observatory-portable-worker-runtime-candidate/v1", + "setup_id": "ai-segmentation-ddrnet-v1", + "source_adapter_sha256": "2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e", + "state": "ready" + }, + { + "adapter_id": "ai-modular-package-worker006-v1-eomt", + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "blockers": [], + "candidate_sha256": "b6c7d84a051bd9c5a163f74cb78bd6aa7a96b6c34e3f5cdfc2f99d4aeca8df7b", + "definition_id": "ai-segmentation-eomt", + "definition_sha256": "387f42bdf707b0e3e357fec1cfb5aa90a64133ebf0095f9b01d749ca2364d47c", + "definition_version": 1, + "executor": { + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721" + }, + "model_manifest_sha256": "94dc40430c2ac23d45aaf14dd26f85f2ca9ba0ec975fe4b08e585c32dd79a223", + "phases": [ + { + "phase_id": "source-materialization", + "state": "implemented" + }, + { + "phase_id": "camera-source", + "state": "implemented" + }, + { + "phase_id": "eomt-inference", + "state": "implemented" + }, + { + "phase_id": "result-assembly", + "state": "implemented" + } + ], + "resource_profile_sha256": "7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d", + "result_contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "reusable_assets": [ + { + "asset_id": "ai-module-agent-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab" + }, + { + "asset_id": "ai-module-definition-registry", + "byte_length": 21610, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30" + }, + { + "asset_id": "camera-source-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561" + }, + { + "asset_id": "eomt-environment", + "byte_length": 211776082, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0" + }, + { + "asset_id": "eomt-ffmpeg-runtime", + "byte_length": 256208352, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69" + }, + { + "asset_id": "eomt-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "211852dfae4ab1acbd1195d4968a385ea56bd7bd3d0c4241a6be7e02794999b7" + }, + { + "asset_id": "eomt-model-cache", + "byte_length": 2552355458, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c" + }, + { + "asset_id": "eomt-package-contract", + "byte_length": 2649, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "3863c4a3f8328221acf66e70dd0cb66c71b0c93b25ef050c072ba351f3edfa5d" + }, + { + "asset_id": "eomt-python-environment", + "byte_length": 5120848705, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20" + }, + { + "asset_id": "eomt-runner-bundle", + "byte_length": 145141, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7" + }, + { + "asset_id": "eomt-transformers-environment", + "byte_length": 225272284, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9" + }, + { + "asset_id": "k1-valid-fov-root", + "byte_length": 6019, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e" + } + ], + "schema_version": "missioncore.observatory-portable-worker-runtime-candidate/v1", + "setup_id": "ai-segmentation-eomt-v1", + "source_adapter_sha256": "2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e", + "state": "ready" + }, + { + "adapter_id": "ai-modular-package-worker006-v1-rf-detr", + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "blockers": [], + "candidate_sha256": "aae136d27d4c013dec111d2b83c22f55df8dcd0dd73a2be5ed47b67f490164f4", + "definition_id": "ai-detection-rf-detr", + "definition_sha256": "598ce44f087c392ee95a024c3c45c95bdd02ad8530a3ccbac13422c2ad2f4a94", + "definition_version": 1, + "executor": { + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721" + }, + "model_manifest_sha256": "edef8446597b801f67538e9e1f056cbb55e56bf61ca4127efd97ce98e7473788", + "phases": [ + { + "phase_id": "source-materialization", + "state": "implemented" + }, + { + "phase_id": "camera-source", + "state": "implemented" + }, + { + "phase_id": "rf-detr-inference", + "state": "implemented" + }, + { + "phase_id": "result-assembly", + "state": "implemented" + } + ], + "resource_profile_sha256": "7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d", + "result_contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "reusable_assets": [ + { + "asset_id": "ai-module-agent-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab" + }, + { + "asset_id": "ai-module-definition-registry", + "byte_length": 21610, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30" + }, + { + "asset_id": "camera-source-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561" + }, + { + "asset_id": "eomt-ffmpeg-runtime", + "byte_length": 256208352, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69" + }, + { + "asset_id": "rf-detr-engine", + "byte_length": 68316388, + "component_id": null, + "kind": "model-artifact", + "model_artifact_role": "tensorrt-engine", + "model_release_id": "rf-detr-large-native-kb4-v1", + "sha256": "b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695" + }, + { + "asset_id": "rf-detr-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "57e5e9bc3033f3dfa696a9135928b8260702a77aadfcaee97a2eb9ccd28d7b48" + }, + { + "asset_id": "rf-detr-package-contract", + "byte_length": 1702, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "00291bebb09af4d615b7670f0f4e5084cd5665d46238a6bb5ff93a76ff95cc18" + }, + { + "asset_id": "rf-detr-valid-fov", + "byte_length": 3668, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63" + } + ], + "schema_version": "missioncore.observatory-portable-worker-runtime-candidate/v1", + "setup_id": "ai-detection-rf-detr-v1", + "source_adapter_sha256": "2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e", + "state": "ready" + }, + { + "adapter_id": "ai-modular-package-worker006-v1-object-distance", + "authority": { + "actuation_allowed": false, + "commands_enabled": false, + "navigation_or_safety_accepted": false, + "production_accepted": false + }, + "blockers": [], + "candidate_sha256": "ec35befdde1a23fb62eda0de582420cd858c9cc7ad46a82f1cf05f07ce2fe39e", + "definition_id": "ai-range-object-distance", + "definition_sha256": "af5e637b78c670930b60cd4527b611aba4af601e6da58aa4dc8326ea6e13c5c2", + "definition_version": 1, + "executor": { + "image_sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab", + "release_id": "ai-modular-installed-package-v1", + "release_sha256": "97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721" + }, + "model_manifest_sha256": "edef8446597b801f67538e9e1f056cbb55e56bf61ca4127efd97ce98e7473788", + "phases": [ + { + "phase_id": "source-materialization", + "state": "implemented" + }, + { + "phase_id": "camera-source", + "state": "implemented" + }, + { + "phase_id": "object-distance-inference", + "state": "implemented" + }, + { + "phase_id": "result-assembly", + "state": "implemented" + } + ], + "resource_profile_sha256": "c244efed459915508044fed4ef0e73c810fbe750e5e379d06723f734bd4385ca", + "result_contract_sha256": "2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305", + "reusable_assets": [ + { + "asset_id": "ai-module-agent-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab" + }, + { + "asset_id": "ai-module-definition-registry", + "byte_length": 21610, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30" + }, + { + "asset_id": "ai-module-m49-profile", + "byte_length": 1683, + "component_id": "m49-tgs-portable-profile-v2", + "kind": "definition-component", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9" + }, + { + "asset_id": "camera-source-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561" + }, + { + "asset_id": "eomt-ffmpeg-runtime", + "byte_length": 256208352, + "component_id": null, + "kind": "local-tree", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69" + }, + { + "asset_id": "k1-camera-lidar-calibration", + "byte_length": 72996000, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "0685d24219d8236caf8b7f1685e93f6d6b59e7fd015a768d88a92bbe8b154944" + }, + { + "asset_id": "object-distance-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "03908003f7531f677fae50ffad12019c6a62ada773f7e84431bfb9c35982c081" + }, + { + "asset_id": "object-distance-package-contract", + "byte_length": 2096, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "7e019064c94884f670d2babecdbd69c6d45082d709ef4cdc6421e3498d1c2c69" + }, + { + "asset_id": "rf-detr-engine", + "byte_length": 68316388, + "component_id": null, + "kind": "model-artifact", + "model_artifact_role": "tensorrt-engine", + "model_release_id": "rf-detr-large-native-kb4-v1", + "sha256": "b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695" + }, + { + "asset_id": "rf-detr-image", + "byte_length": null, + "component_id": null, + "kind": "container-image", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "57e5e9bc3033f3dfa696a9135928b8260702a77aadfcaee97a2eb9ccd28d7b48" + }, + { + "asset_id": "rf-detr-valid-fov", + "byte_length": 3668, + "component_id": null, + "kind": "local-file", + "model_artifact_role": null, + "model_release_id": null, + "sha256": "a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63" + } + ], + "schema_version": "missioncore.observatory-portable-worker-runtime-candidate/v1", + "setup_id": "ai-range-object-distance-v1", + "source_adapter_sha256": "4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de", + "state": "ready" + } + ], + "schema_version": "missioncore.observatory-portable-worker-runtime-registry/v1" +} diff --git a/deploy/laboratory/Dockerfile b/deploy/laboratory/Dockerfile new file mode 100644 index 00000000..9db296a1 --- /dev/null +++ b/deploy/laboratory/Dockerfile @@ -0,0 +1,19 @@ +FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df +WORKDIR /opt/nodedc/laboratory +COPY requirements.lock ./requirements.lock +RUN python3 -m pip install --no-cache-dir --require-hashes -r requirements.lock +COPY src ./src +COPY packages/plugin-sdk/python ./plugin +COPY config ./config +ENV PYTHONPATH=/opt/nodedc/laboratory/src:/opt/nodedc/laboratory/plugin \ + PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 \ + MISSIONCORE_LAB_RUNTIME_ROLE=worker MISSIONCORE_LAB_RUNTIME_ROOT=/lab \ + MISSIONCORE_LAB_CONFIGURATION_ROOT=/opt/nodedc/laboratory/config \ + MISSIONCORE_LAB_TOKEN_FILE=/run/secrets/lab-token +RUN python3 -B -c "from k1link.laboratory.worker_server import create_app; assert callable(create_app)" +ARG NODEDC_SOURCE_TREE_SHA256 +LABEL com.nodedc.product="mission-core" com.nodedc.stack="laboratory" \ + com.nodedc.role="evidence-service" com.nodedc.managed-by="laboratory-deployment-v1" \ + com.nodedc.source-tree.sha256="${NODEDC_SOURCE_TREE_SHA256}" +ENTRYPOINT ["python3"] +CMD ["-m", "uvicorn", "k1link.laboratory.worker_server:create_app", "--factory", "--host", "0.0.0.0", "--port", "8080", "--limit-concurrency", "8", "--no-access-log"] diff --git a/deploy/laboratory/README.md b/deploy/laboratory/README.md new file mode 100644 index 00000000..603e7214 --- /dev/null +++ b/deploy/laboratory/README.md @@ -0,0 +1,160 @@ +# Worker LAB service + +This deployment moves the existing LAB evidence readers, bounded visualization +preparation and evaluation adapters off the operator. It preserves their API and +viewer contracts. It does not add another scheduler, model-training orchestrator, +or UI. New packaged LAB jobs keep using the installed-package Worker executor. + +## Reproducible runtime + +`Dockerfile` pins the Python base image by digest; `requirements.lock` pins Python +artifacts and hashes. Build from the repository source, plugin SDK and `config`: +copy `Dockerfile` and `requirements.lock` to a bounded build context containing +`src/`, `packages/plugin-sdk/python/`, and `config/`. Seal a manifest of source +paths, sizes and SHA-256 values; pass its identity as `NODEDC_SOURCE_TREE_SHA256`. +Use the resulting immutable image digest in Compose, not a mutable `latest` tag. +The image has no models, private evidence, host credential or Docker socket. + +Configure these deployment bindings, separately from artifact identities: + +| Variable | Meaning | +| --- | --- | +| `LAB_IMAGE` | Built `sha256:…` image identity | +| `LAB_RUNTIME` | Existing portable Worker LAB directory, mounted at `/lab` | +| `LAB_ARCHIVE` | Dedicated LAB archive volume, `/lab-archive` | +| `LAB_AI_JOBS` | Admitted AI executor jobs/sources volume, `/ai-jobs` | +| `LAB_TGS_JOBS` | Admitted TGS executor volume, `/tgs-jobs` | +| `LAB_CONFIGURATION` | That release's verified `config/`, mounted read-only at `/lab/config` | +| `LAB_TOKEN_FILE` | Private bearer credential file, mounted read-only | +| `LAB_FFMPEG_ROOT` | Sealed Linux FFmpeg/FFprobe asset tree with `bin/ffmpeg` and `bin/ffprobe` | +| `LAB_PORT` | Host loopback port, default 19087 | + +The existing deployment uses the independently verified FFmpeg 7.0.2 asset. +Validate its tree manifest/digests before binding it. It is an external portable +runtime asset, not an implicit host-installed executable. Requalification on a +new CPU/OS requires the matching Linux image/asset architecture. + +Run `docker compose -f compose.yaml up -d --pull never` with those bindings. +The service is `ndc-laboratory-evidence` in project `ndc-laboratory`. It runs with a +read-only root, 2 CPU / 4 GiB / 128 PID limits, a 512 MiB tmpfs, dropped +capabilities and rotating logs. It is reachable only on host loopback; the token +is required for health and API calls. Never publish the bearer token in command +arguments or logs. Persist its host file with owner-only access. + +## Volume and migration + +The existing immutable archive is **not** the mutable working volume. Explicit +one-time materialization uses: + +``` +python -m k1link.laboratory.materialize_archive --archive /archive --target /lab +``` + +Run only as Worker with the archive read-only and the intended LAB volume writable. +The module verifies every file and seals `state/materialization.json`. Existing +conflicting files stop migration; they are not overwritten. Resume is by verified +content. The volume remains separate from both source releases and image layers. +For legacy catalogs ordered by mtime, preserve the reviewed original directory +metadata separately; hash-valid contents alone do not preserve result ordering. + +Recorded camera preparation uses the existing Worker source CAS, never a Core +fallback. `materialize_recorded_sources` accepts a digest-bound import manifest, +checks source members and prepared-media timelines, and publishes bindings only +after validation. Replacing bindings requires the previous digest. Original +camera archives and accepted operator recordings stay preserved. Ready canonical +RRDs are indexed by `recorded-sources/canonical-recordings.json` and verified before +use. Host filesystem paths are deployment bindings, not source identities. + +The legacy evidence volume layout retains `.runtime/compute-*` paths to reuse +validated readers. They are under **Worker `/lab`**, not the operator checkout. +Generated viewing products go to `/lab/presentation`; manual annotations have +separate provenance. No automatic age-based deletion is admitted. + +## Operator connection + +Core reads `.runtime/mission-core/laboratory-worker-gateway.json`: + +```json +{ + "schema_version": "missioncore.laboratory-worker-gateway/v1", + "base_url": "http://127.0.0.1:19087", + "token_file": "laboratory-worker.token" +} +``` + +Keep the credential separate (mode 0600 on POSIX). For a remote Worker use the +existing authenticated SSH alias with a loopback-only forward, or a verified +HTTPS endpoint. Plain remote HTTP, redirects and proxy-environment substitution +are rejected. The Mac managed SSH link uses `com.nodedc.mission-core.laboratory-worker-link` +with bounded logging and automatic reconnect; it does not change VPN/routes. +`install_operator_link.py` writes this versioned binding on macOS. It refuses to +overwrite a different existing definition. Other platforms can provide the same +loopback transport with their service manager; macOS launchd is not baked into +the Worker image. + +Core forwards LAB/LiDAR requests and the perception recording/media endpoints. +Transport limits: 8 concurrent requests, 8 MiB request body, 2 GiB response, +5-second connect timeout, 60-second read timeout (360 for bounded RRD preparation). +Range, ETag, compressed points and Rerun headers are preserved. No automatic retry +of writes and no staging of whole responses on Core. Worker unavailable means +503; never run a local reader/model as fallback. + +## Acceptance, rollback and lifecycle + +1. Verify ownership, immutable archive, camera and supplemental evidence receipts. +2. Start the exact image; authenticate `/health`; compare existing catalog choices. +3. Run `verify_runtime.py` inside the installed container. Its tiny synthetic + clips verify that 20 selected frames stay 20 with correct Rerun timestamps. +4. Verify real camera frames, segmentation video ranges, full RRD transfer and + 3D timeline chunks (start/middle/end). Inspect Play/seek in the existing UI. +5. Switch only the canonical Core service. Preserve its data and UI; never start + an alternate Core on another port. +6. Retire only archived local working files whose current hashes still match, + after the previous local process has stopped. Leave changed/unknown files and + all scans/maps/captures/accepted operator recordings. Record actual freed disk. + +Rollback selects the previous verified service image/configuration on the same +volume. Do not rollback or overwrite annotations, sources or accepted results. +Keep one verified rollback release; retire only this deployment's superseded +build contexts/images after no container or active task uses them. Never use a +global Docker prune. The archive can restore explicitly selected files if needed. + +The 128 GiB restore-admission budget and 40 GiB free reserve are not a hard volume +quota. Existing per-product cache publication budgets apply; exhaustion refuses +new copies rather than evicting recovery data. Active jobs and unknown ownership +block cleanup. Long-term retained experiment growth still requires explicit +retention decisions on Worker. The operator must not become the spillover disk. + +## Explicit user deletion + +The authenticated `POST /api/v1/laboratory/data-deletions` accepts only opaque +`owner_ids`. `MISSIONCORE_LAB_DELETION_ROOTS` is supplied by Compose, mapping +`lab`, `archive`, `ai`, `tgs` to bound volumes. All bindings must be present. +It inventories only admitted producer layouts, protects references shared with +retained owners, validates paths and deletes owned files. Failed operations are +retryable; receipts in `/lab/state/data-ownership` contain identities/status. +`/lab-archive/deleted-members.json` prevents legacy restore from resurrecting +explicitly deleted results. These are bounded metadata, not retained LAB bytes. + +The archive mount is writable only because this service now owns explicit LAB +destruction. There is no age-based archive purge. Generic runtime roots, source +CAS, images, plugins and unrelated datasets are outside the deletion bindings. +The low-disk reserve must not block authorized cleanup itself. Requalification +must cover shared content, interrupted deletion and actual playback of keepers. + + +## Retiring the fixed LAB V1 agent + +`retire_fixed_lab_v1.ps1` is the reviewed one-time migration for the standalone +EoMT+DDRNet agent. Core must first remove its setup from admission and verify that +no old job is active. The script checks the exact predecessor container ID/image, +current modular/TGS agents and absence of a separate scheduled legacy launcher. +It persists a retirement receipt under the supplied runtime root before removal. +It never prunes images, mounts, models, environments or experiment data. + +Applied on Worker 006 on 8 November 2026. Do not rerun the predecessor migration +against another container. The active modular builder reads shared model assets +from `k1link.observatory.modular_model_assets`; its legacy promotion CLI is retired. +Rollback of compute admission requires a deliberate versioned registry/runtime +change; do not launch the frozen compatibility fixtures as current configuration. +See `outputs/lab-retirement-transport-20261108/REPORT.md` for IDs and evidence. diff --git a/deploy/laboratory/compose.yaml b/deploy/laboratory/compose.yaml new file mode 100644 index 00000000..aadcdcef --- /dev/null +++ b/deploy/laboratory/compose.yaml @@ -0,0 +1,60 @@ +name: ndc-laboratory +services: + evidence: + image: ${LAB_IMAGE:?immutable LAB image required} + container_name: ndc-laboratory-evidence + restart: unless-stopped + read_only: true + init: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + cpus: 2 + mem_limit: 4g + pids_limit: 128 + ports: ["127.0.0.1:${LAB_PORT:-19087}:8080"] + environment: + MISSIONCORE_LAB_FFMPEG: /opt/ffmpeg/bin/ffmpeg + MISSIONCORE_LAB_CONFIGURATION_ROOT: /lab/config + MISSIONCORE_LAB_DELETION_ROOTS: '{"lab":"/lab","archive":"/lab-archive","ai":"/ai-jobs","tgs":"/tgs-jobs"}' + tmpfs: ["/tmp:size=536870912,mode=1777"] + volumes: + - type: bind + source: ${LAB_RUNTIME:?portable LAB volume required} + target: /lab + - type: bind + source: ${LAB_ARCHIVE:?portable LAB archive required} + target: /lab-archive + - type: bind + source: ${LAB_AI_JOBS:?AI job data required} + target: /ai-jobs + - type: bind + source: ${LAB_TGS_JOBS:?TGS job data required} + target: /tgs-jobs + - type: bind + source: ${LAB_CONFIGURATION:?versioned LAB configuration required} + target: /lab/config + read_only: true + - type: bind + source: ${LAB_TOKEN_FILE:?private token required} + target: /run/secrets/lab-token + read_only: true + - type: bind + source: ${LAB_FFMPEG_ROOT:?sealed FFmpeg runtime required} + target: /opt/ffmpeg + read_only: true + logging: + driver: json-file + options: {max-size: "10m", max-file: "2"} + labels: + com.nodedc.product: mission-core + com.nodedc.stack: laboratory + com.nodedc.role: evidence-service + com.nodedc.managed-by: laboratory-deployment-v1 +networks: + default: + name: ndc-laboratory + labels: + com.nodedc.product: mission-core + com.nodedc.stack: laboratory + com.nodedc.role: transport + com.nodedc.managed-by: laboratory-deployment-v1 diff --git a/deploy/laboratory/install_operator_link.py b/deploy/laboratory/install_operator_link.py new file mode 100644 index 00000000..c9fdb1dc --- /dev/null +++ b/deploy/laboratory/install_operator_link.py @@ -0,0 +1,74 @@ +"""Versioned macOS operator-to-Worker transport binding; dry-run by default.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import plistlib +import re +import subprocess +import sys +from pathlib import Path + +LABEL = "com.nodedc.mission-core.laboratory-worker-link" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--worker", required=True, help="Existing SSH configuration alias") + parser.add_argument("--port", type=int, default=19087) + parser.add_argument("--worker-port", type=int, default=19087) + actions = parser.add_mutually_exclusive_group() + actions.add_argument("--apply", action="store_true") + actions.add_argument("--remove", action="store_true") + args = parser.parse_args() + if sys.platform != "darwin": + parser.error("This binding uses macOS launchd; Worker itself is platform-neutral") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}", args.worker): + parser.error("Use an existing SSH alias") + if not all(1024 <= p <= 65535 for p in (args.port, args.worker_port)): + parser.error("Ports must be between 1024 and 65535") + core = Path(__file__).resolve().parents[2] + sys.path.insert(0, str(core / "src")) + from k1link.launchd_logs import bounded_launchd_output, launchd_log_path, prepare_launchd_log + log = launchd_log_path("laboratory-worker-link.log") + document = bounded_launchd_output({ + "Label": LABEL, + "ProgramArguments": ["/usr/bin/ssh", "-N", "-T", "-o", "BatchMode=yes", + "-o", "StrictHostKeyChecking=yes", "-o", "ExitOnForwardFailure=yes", + "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15", + "-o", "ServerAliveCountMax=3", "-o", "PermitLocalCommand=no", + "-o", "ForwardAgent=no", "-L", + f"127.0.0.1:{args.port}:127.0.0.1:{args.worker_port}", args.worker], + "KeepAlive": True, "RunAtLoad": True, "ThrottleInterval": 15, "ExitTimeOut": 10, + "StandardOutPath": str(log), "StandardErrorPath": str(log), + }, core) + payload = plistlib.dumps(document, sort_keys=True) + path = Path.home() / "Library/LaunchAgents" / (LABEL + ".plist") + if path.is_symlink() or (path.exists() and path.read_bytes() != payload): + raise RuntimeError("Existing link differs; preserve it and review the deployment binding") + target = f"gui/{os.getuid()}/{LABEL}" + if args.remove: + if path.exists(): + loaded = subprocess.run(["launchctl", "print", target], capture_output=True) + if loaded.returncode == 0: + subprocess.run(["launchctl", "bootout", target], check=True) + path.unlink() + elif args.apply: + prepare_launchd_log(log) + path.parent.mkdir(parents=True, exist_ok=True) + if not path.exists(): + with path.open("xb") as output: + output.write(payload) + path.chmod(0o600) + probe = subprocess.run(["launchctl", "print", target], capture_output=True) + if probe.returncode: + subprocess.run(["launchctl", "bootstrap", f"gui/{os.getuid()}", str(path)], check=True) + print(json.dumps({"label": LABEL, "port": args.port, + "sha256": hashlib.sha256(payload).hexdigest(), + "action": "remove" if args.remove else "apply" if args.apply else "plan"})) + + +if __name__ == "__main__": + main() diff --git a/deploy/laboratory/requirements.lock b/deploy/laboratory/requirements.lock new file mode 100644 index 00000000..aec38cdb --- /dev/null +++ b/deploy/laboratory/requirements.lock @@ -0,0 +1,452 @@ +# This file was autogenerated by uv via the following command: +annotated-doc==0.0.4 \ + --hash=sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320 \ + --hash=sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4 + # via + # fastapi + # typer +annotated-types==0.7.0 \ + --hash=sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53 \ + --hash=sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89 + # via pydantic +anyio==4.14.2 \ + --hash=sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494 \ + --hash=sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f + # via + # httpx + # starlette + # watchfiles +attrs==26.1.0 \ + --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \ + --hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32 + # via rerun-sdk +bleak==3.0.2 \ + --hash=sha256:39092feb9e83f1df5ad2f88e837723c7211c982ce9e9cda6235104bc2ebe0d0d \ + --hash=sha256:c2229cb8238d5876b4bd05c74bf7a1aea1f88da39d2e51ac9dfd5cc319d5265f + # via nodedc-mission-core +certifi==2026.7.22 \ + --hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 \ + --hash=sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55 + # via + # httpcore + # httpx +cffi==2.1.1 ; platform_python_implementation != 'PyPy' \ + --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \ + --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \ + --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \ + --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \ + --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \ + --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \ + --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \ + --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \ + --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \ + --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \ + --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \ + --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \ + --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf + # via cryptography +click==8.4.2 \ + --hash=sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6 \ + --hash=sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76 + # via uvicorn +colorama==0.4.6 ; sys_platform == 'win32' \ + --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \ + --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 + # via + # click + # typer +cryptography==46.0.7 \ + --hash=sha256:128c5edfe5e5938b86b03941e94fac9ee793a94452ad1365c9fc3f4f62216832 \ + --hash=sha256:1d25aee46d0c6f1a501adcddb2d2fee4b979381346a78558ed13e50aa8a59067 \ + --hash=sha256:24402210aa54baae71d99441d15bb5a1919c195398a87b563df84468160a65de \ + --hash=sha256:35719dc79d4730d30f1c2b6474bd6acda36ae2dfae1e3c16f2051f215df33ce0 \ + --hash=sha256:397655da831414d165029da9bc483bed2fe0e75dde6a1523ec2fe63f3c46046b \ + --hash=sha256:420b1e4109cc95f0e5700eed79908cef9268265c773d3a66f7af1eef53d409ef \ + --hash=sha256:42a1e5f98abb6391717978baf9f90dc28a743b7d9be7f0751a6f56a75d14065b \ + --hash=sha256:462ad5cb1c148a22b2e3bcc5ad52504dff325d17daf5df8d88c17dda1f75f2a4 \ + --hash=sha256:506c4ff91eff4f82bdac7633318a526b1d1309fc07ca76a3ad182cb5b686d6d3 \ + --hash=sha256:5ad9ef796328c5e3c4ceed237a183f5d41d21150f972455a9d926593a1dcb308 \ + --hash=sha256:5d1c02a14ceb9148cc7816249f64f623fbfee39e8c03b3650d842ad3f34d637e \ + --hash=sha256:5e51be372b26ef4ba3de3c167cd3d1022934bc838ae9eaad7e644986d2a3d163 \ + --hash=sha256:73510b83623e080a2c35c62c15298096e2a5dc8d51c3b4e1740211839d0dea77 \ + --hash=sha256:7bbc6ccf49d05ac8f7d7b5e2e2c33830d4fe2061def88210a126d130d7f71a85 \ + --hash=sha256:84d4cced91f0f159a7ddacad249cc077e63195c36aac40b4150e7a57e84fffe7 \ + --hash=sha256:8a469028a86f12eb7d2fe97162d0634026d92a21f3ae0ac87ed1c4a447886c83 \ + --hash=sha256:91bbcb08347344f810cbe49065914fe048949648f6bd5c2519f34619142bbe85 \ + --hash=sha256:935ce7e3cfdb53e3536119a542b839bb94ec1ad081013e9ab9b7cfd478b05006 \ + --hash=sha256:9694078c5d44c157ef3162e3bf3946510b857df5a3955458381d1c7cfc143ddb \ + --hash=sha256:a1529d614f44b863a7b480c6d000fe93b59acee9c82ffa027cfadc77521a9f5e \ + --hash=sha256:abad9dac36cbf55de6eb49badd4016806b3165d396f64925bf2999bcb67837ba \ + --hash=sha256:b36a4695e29fe69215d75960b22577197aca3f7a25b9cf9d165dcfe9d80bc325 \ + --hash=sha256:cbd5fb06b62bd0721e1170273d3f4d5a277044c47ca27ee257025146c34cbdd1 \ + --hash=sha256:cdf1a610ef82abb396451862739e3fc93b071c844399e15b90726ef7470eeaf2 \ + --hash=sha256:cdfbe22376065ffcf8be74dc9a909f032df19bc58a699456a21712d6e5eabfd0 \ + --hash=sha256:d23c8ca48e44ee015cd0a54aeccdf9f09004eba9fc96f38c911011d9ff1bd457 \ + --hash=sha256:e4cfd68c5f3e0bfdad0d38e023239b96a2fe84146481852dffbcca442c245aa5 \ + --hash=sha256:ea42cbe97209df307fdc3b155f1b6fa2577c0defa8f1f7d3be7d31d189108ad4 \ + --hash=sha256:f247c8c1a1fb45e12586afbb436ef21ff1e80670b2861a90353d9b025583d246 + # via nodedc-mission-core +dbus-fast==5.0.22 ; sys_platform == 'linux' \ + --hash=sha256:34dc67d7d21a12399828dd13e63b352750580beea54ea7c729e708f2d2905fef \ + --hash=sha256:4ffcf16034f71a801bd2108aeffb6337d104c9459e8b1a218d16a917c8a2d2e9 \ + --hash=sha256:7d1c42963235cfc015a2d2b8c5fe42b65387493b4ad4ce0ec122601c805e6742 \ + --hash=sha256:855f15b7f7805171da2b82de1c317d01cfbb9fb8ac61fcc1e8dec54d8c69fab7 \ + --hash=sha256:8f0bcad7f71d2304a68a5b0bc0d24c3fcc14710a2ffcf5f2a27521e3aece71ca \ + --hash=sha256:98de6d2c200d8182e1fd0bdde3206fa556b8fa14ebb752a044cd8daa87b4658c \ + --hash=sha256:b013437b66dc22b8d9aca5e0b0d46bf1980208a143409469fe482d9684a2a717 \ + --hash=sha256:f72b77be63f7bb24cf42936ad10994d40f43fed691f857f7854b5882d6a5227c + # via bleak +fastapi==0.139.0 \ + --hash=sha256:99ab7b2d92223c76d6cf10757ab3f89d45b38267fc20b2a136cf02f6beac3145 \ + --hash=sha256:cf15e1e9e667ddb0ad63811e60bd11390d1aac838ca4a7a23f421807b2308189 + # via nodedc-mission-core +foxglove-sdk==0.25.3 \ + --hash=sha256:139bb1f2ae284673ecb17a1b47955989a58ab3a8639c1fd0f6d3f3afbbbd0fda \ + --hash=sha256:18d7dd5e61afc65163438b858a70bec3a30126de1664a97358d4403e20db5eb1 \ + --hash=sha256:2dbdef29d2b6115bbbc478f309ac4937fb8765b42681537db99a15282ebaac6f \ + --hash=sha256:32f1066401c37538d478b4a8ecaaae4e9dd019f9f75d3ef47494bfe7d4273dee \ + --hash=sha256:3d9e671be05e7539a99d84dbd254581616f7ebae8ee8430766788dd6093d58a3 \ + --hash=sha256:510c7fe47c45428e9d76eddfae1b9966b7976819a3a194a00f7e8d0f4b3eacc3 \ + --hash=sha256:9667615b342651b3960dd82e6a8403678c1fc701799bf0b28e41be0392eb507d \ + --hash=sha256:a2a1716cade8a9dd842df18f7b1306a9931fa114f485fc552fc14c44ddba8351 \ + --hash=sha256:ac881ae307ba432766e6141d9098ced2059838226d225fbeb20de1c57d782a9f \ + --hash=sha256:bcc894b88188d8169973cfbb1370300f671760adea9d6e9447e5a03b2289527d \ + --hash=sha256:d88faf89da6da3d904b6aa1371b809f4d9dcabb8981fcedcfafccdf07b200a49 \ + --hash=sha256:dcdcb054c198e892ac271c88e685e292d1ef8f1f21a14e2d3a9de5988474e60a \ + --hash=sha256:e00cdb87d0a1623cd60a66f7fd531bf492164433e313d4c7f77cb42fdd613420 + # via nodedc-mission-core +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + # via + # httpcore + # uvicorn +httpcore==1.0.9 \ + --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \ + --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 + # via httpx +httptools==0.8.0 \ + --hash=sha256:425f83884fd6343828d8c565f046cb72b6d19063f6924093e11bcd8e1548cd09 \ + --hash=sha256:5931891fb7b441b8a3853cf1b85c82c903defce084dd5f6771ca46e31bf862c5 \ + --hash=sha256:6b2a32f18d97e16e90827d7a819ffa8dbd8cc245fc4e1fa9d1095b54ef4bd999 \ + --hash=sha256:880490234c10f70a9830743097e8958d6e4b9f5a0ffc24515023afeef984054d \ + --hash=sha256:a1afd7c9fbff0d9f5d489c4ce2768bd09c84a46ddefc7161e6aa82ae35c85745 \ + --hash=sha256:b15fc622b0f869d19207c4089a501d9bcc63ca5e071ffdd2f03f922df882dcb2 \ + --hash=sha256:cd96f29b4bab1d42fa6e3d008711c75e0f79e94e06827330160e3a304227f150 \ + --hash=sha256:ef7c3c97f4311c7be57e2986629df89d49cb434dbff78eafcd48c2bff986b15a + # via uvicorn +httpx==0.28.1 \ + --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \ + --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad + # via nodedc-mission-core +idna==3.18 \ + --hash=sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2 \ + --hash=sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848 + # via + # anyio + # httpx +lz4==4.4.5 \ + --hash=sha256:214e37cfe270948ea7eb777229e211c601a3e0875541c1035ab408fbceaddf50 \ + --hash=sha256:24092635f47538b392c4eaeff14c7270d2c8e806bf4be2a6446a378591c5e69e \ + --hash=sha256:2c3ea562c3af274264444819ae9b14dbbf1ab070aff214a05e97db6896c7597e \ + --hash=sha256:5f0b9e53c1e82e88c10d7c180069363980136b9d7a8306c4dca4f760d60c39f0 \ + --hash=sha256:6d0bf51e7745484d2092b3a51ae6eb58c3bd3ce0300cf2b2c14f76c536d5697a \ + --hash=sha256:713a777de88a73425cf08eb11f742cd2c98628e79a8673d6a52e3c5f0c116f33 \ + --hash=sha256:7b62f94b523c251cf32aa4ab555f14d39bd1a9df385b72443fd76d7c7fb051f5 \ + --hash=sha256:a88cbb729cc333334ccfb52f070463c21560fca63afcf636a9f160a55fac3301 \ + --hash=sha256:df5aa4cead2044bab83e0ebae56e0944cc7fcc1505c7787e9e1057d6d549897e + # via nodedc-mission-core +markdown-it-py==4.2.0 \ + --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \ + --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a + # via rich +mdurl==0.1.2 \ + --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \ + --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba + # via markdown-it-py +numpy==2.5.1 \ + --hash=sha256:08d60c810432eb83360958dea0999ac4cfb94531ea8efcbf0b7f277c2068aeb2 \ + --hash=sha256:17a25e09640602e10bc8de0e6fa2b3fd68eedd84ba6d7842dc8f32f9ab87bd0b \ + --hash=sha256:2ae0ca40bcb22d6ba59c1dfd5446f49940b0f2d821fde133f10dda11f816b84e \ + --hash=sha256:2c889b56fe48b1018f764b0eec8df59ab654e9148aa91faa12596043500de277 \ + --hash=sha256:59fda5e192b570217ec2580c96f00e9a7e12ef6866a900eb089b62c1a32545ca \ + --hash=sha256:61ac47e772e6b8ea489e1d2f441a34c5c3ac17327e7ce294cbdf535795ad4e75 \ + --hash=sha256:78798bd5b9ad744056af8efa90e3b9ddaa53272a0848a483084a1cc0a13b2dc0 \ + --hash=sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3 \ + --hash=sha256:ab451b59c5643c570974c43aef780703ef1d3b4965d2be07afd530615a9358d1 \ + --hash=sha256:e824c2acf8862052246be5a44c15da1777940c60d010dd2aab897824d9c430f9 \ + --hash=sha256:f7119ebff1a9829e9f431a4f9d28e703023bb6b9fe7c8f724467dbfc27c94ab3 \ + --hash=sha256:f7d60026c0bdb1380e83bfa7a0419c4577ee4b9a08880afcb6dadeb74c649fa2 + # via rerun-sdk +paho-mqtt==2.1.0 \ + --hash=sha256:12d6e7511d4137555a3f6ea167ae846af2c7357b10bc6fa4f7c3968fc1723834 \ + --hash=sha256:6db9ba9b34ed5bc6b6e3812718c7e06e2fd7444540df2455d2c51bd58808feee + # via nodedc-mission-core +pillow==12.3.0 \ + --hash=sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df \ + --hash=sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510 \ + --hash=sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce \ + --hash=sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91 \ + --hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09 \ + --hash=sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965 \ + --hash=sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9 \ + --hash=sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f \ + --hash=sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c \ + --hash=sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7 + # via + # nodedc-mission-core + # rerun-sdk +psutil==7.2.2 \ + --hash=sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372 \ + --hash=sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9 \ + --hash=sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979 \ + --hash=sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee \ + --hash=sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e \ + --hash=sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc \ + --hash=sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988 \ + --hash=sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486 \ + --hash=sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8 + # via rerun-sdk +pyarrow==25.0.0 \ + --hash=sha256:0721332c30fdd453fdd1fc203b2ac1f4c9db5aea28fa38d41f2574c4b068b9ec \ + --hash=sha256:149730a3d1f0fb59d663a0b8aa210adfd9c17c27cd94a0d143e60daea8320d4e \ + --hash=sha256:20887a762dd61dcc530f93a140840ab1f6aa7836b33270e42d627ab3cf11e537 \ + --hash=sha256:3f356afe61186395c861d5cd63dc21ff7d5fa335012a4668d979257df7fea0f5 \ + --hash=sha256:58d1ab556b0cea1c93fdb799b24ad58adb2f2a2788dbce782a94f64ae1a5cc9b \ + --hash=sha256:5d1dbf24e151042f2fa3c129563f65d66674128868496fb008c4272b16bdf778 \ + --hash=sha256:d2d697008b5ec06d75952ef260c2e9a8a0f6ccfce24266c04c9c8ade927cb3b4 \ + --hash=sha256:fa1482b3da10cac2d4db6e26b81da543e237616af2ef6d466018b31ca586496f + # via rerun-sdk +pycparser==3.0 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' \ + --hash=sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29 \ + --hash=sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992 + # via cffi +pydantic==2.13.4 \ + --hash=sha256:45a282cde31d808236fd7ea9d919b128653c8b38b393d1c4ab335c62924d9aba \ + --hash=sha256:c40756b57adaa8b1efeeced5c196f3f3b7c435f90e84ea7f443901bec8099ef6 + # via + # fastapi + # missioncore-plugin-sdk +pydantic-core==2.46.4 \ + --hash=sha256:00c603d540afdd6b80eb39f078f33ebd46211f02f33e34a32d9f053bba711de0 \ + --hash=sha256:1d8ba486450b14f3b1d63bc521d410ec7565e52f887b9fb671791886436a42f7 \ + --hash=sha256:3009f12e4e90b7f88b4f9adb1b0c4a3d58fe7820f3238c190047209d148026df \ + --hash=sha256:3245406455a5d98187ec35530fd772b1d799b26667980872c8d4614991e2c4a2 \ + --hash=sha256:3a233125ac121aa3ffba9a2b59edfc4a985a76092dc8279586ab4b71390875e7 \ + --hash=sha256:4fc73cb559bdb54b1134a706a2802a4cddd27a0633f5abb7e53056268751ac6a \ + --hash=sha256:56cb4851bcaf3d117eddcef4fe66afd750a50274b0da8e22be256d10e5611987 \ + --hash=sha256:5b712b53160b79a5850310b912a5ef8e57e56947c8ad690c227f5c9d7e561712 \ + --hash=sha256:62f875393d7f270851f20523dd2e29f082bcc82292d66db2b64ea71f64b6e1c1 \ + --hash=sha256:8233f2947cf85404441fd7e0085f53b10c93e0ee78611099b5c7237e36aacbf7 \ + --hash=sha256:8d0820e8192167f80d88d64038e609c31452eeca865b4e1d9950a27a4609b00b \ + --hash=sha256:926c9541b14b12b1681dca8a0b75feb510b06c6341b70a8e500c2fdcff837cce \ + --hash=sha256:9401557acd873c3a7f3eb9383edef8ac4968f9510e340f4808d427e75667e7b4 \ + --hash=sha256:962ccbab7b642487b1d8b7df90ef677e03134cf1fd8880bf698649b22a69371f \ + --hash=sha256:9aa768456404a8bf48a4406685ac2bec8e72b62c69313734fa3b73cf33b3a894 \ + --hash=sha256:ad785e92e6dc634c21555edc8bd6b64957ab844541bcb96a1366c202951ae526 \ + --hash=sha256:b2f69dec1725e79a012d920df1707de5caf7ed5e08f3be4435e25803efc47458 \ + --hash=sha256:c68fcd102d71ea85c5b2dfac3f4f8476eff42a9e078fd5faefff6d145063536b \ + --hash=sha256:e9c26f834c65f5752f3f06cb08cb86a913ceb7274d0db6e267808a708b46bc89 \ + --hash=sha256:fbdb89b3e1c94a30cc5edfce477c6e6a5dc4d8f84665b455c27582f211a1c72c + # via pydantic +pygments==2.20.0 \ + --hash=sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f \ + --hash=sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176 + # via rich +pyobjc-core==12.2.1 ; sys_platform == 'darwin' \ + --hash=sha256:7a7b9b018402342cf32bf1956366896350fbe5c0478cb3ef59778f77abed7f07 \ + --hash=sha256:a64232bb27ed101d4adc7d42b0e64a6d3331aac7bee7861c037a6777a163f10b + # via + # bleak + # pyobjc-framework-cocoa + # pyobjc-framework-corebluetooth + # pyobjc-framework-libdispatch +pyobjc-framework-cocoa==12.2.1 ; sys_platform == 'darwin' \ + --hash=sha256:28b9b8bab1c36efb94744786918752d0c1842f5fbb67e7d5ca97b5f736512080 \ + --hash=sha256:b94b37fe5730e5ae1fb0052912cd174e6ec329b0bfba4a012ae5db1014b5864b + # via + # pyobjc-framework-corebluetooth + # pyobjc-framework-libdispatch +pyobjc-framework-corebluetooth==12.2.1 ; sys_platform == 'darwin' \ + --hash=sha256:2f8d2ed65c0e98ba044b6a7fc2f9a290a5c579a28d33a57c642f8617ccbcca0f \ + --hash=sha256:7dbb285295097205bebbcb11f55161e5faa02111108fb7b17536176e31971eb0 + # via bleak +pyobjc-framework-libdispatch==12.2.1 ; sys_platform == 'darwin' \ + --hash=sha256:0d24eda41c6c258135077f60d410e704bc7b5a67adcb2ca463918896c7363795 \ + --hash=sha256:8f41b5021ff70bc51220a79b41ebd1eacb55fe3ceb67448594f30e491a2c42a5 + # via bleak +python-dotenv==1.2.2 \ + --hash=sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a \ + --hash=sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3 + # via uvicorn +pyyaml==6.0.3 \ + --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \ + --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \ + --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \ + --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \ + --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \ + --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \ + --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \ + --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \ + --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \ + --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \ + --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0 + # via + # nodedc-mission-core + # uvicorn +rerun-sdk==0.36.3 \ + --hash=sha256:287059b7154bf3881f5b32035f5772d0556d55a0a894650fb74a2605fb39afbe \ + --hash=sha256:804067d6e71747f8461104988be82543b318b583a2837935558a5e79a5e9befd \ + --hash=sha256:954d8980e15e71245ac91ba7120bbaeb624df2bd7a47bbbb8856fd45174d2521 \ + --hash=sha256:f84441a3e1d1d679f6fe5a319cac86ccc3992f8f88bfa72517f76d8b45bf066c + # via nodedc-mission-core +rich==14.3.4 \ + --hash=sha256:07e7adb4690f68864777b1450859253bed81a99a31ac321ac1817b2313558952 \ + --hash=sha256:817e02727f2b25b40ef56f5aa2217f400c8489f79ca8f46ea2b70dd5e14558a9 + # via + # nodedc-mission-core + # typer +shellingham==1.5.4 \ + --hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686 \ + --hash=sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de + # via typer +starlette==1.3.1 \ + --hash=sha256:05d0213193f2fbaae60e2ecb593b4add4262ad4e46536b54abe36f11a71724e0 \ + --hash=sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6 + # via fastapi +typer==0.26.8 \ + --hash=sha256:3512ca79ac5c11113414b36e80281b872884477722440691c89d1112e321a49c \ + --hash=sha256:c244a6bd558886fe3f8780efb6bdd28bb9aff005a94eedebaa5cb32926fe2f7e + # via nodedc-mission-core +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via + # anyio + # fastapi + # pydantic + # pydantic-core + # rerun-sdk + # starlette + # typing-inspection + # winrt-runtime +typing-inspection==0.4.2 \ + --hash=sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7 \ + --hash=sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464 + # via + # fastapi + # pydantic +uvicorn==0.51.0 \ + --hash=sha256:5d38af6cd620f2ae3849fb44fd4879e0890aa1febe8d47eb355fb45d93fe6a5b \ + --hash=sha256:f6f4b69b657c312f516dd2d268ab9ae6f254b11e4bac504f37b2ab58b24dd0b0 + # via nodedc-mission-core +uvloop==0.22.1 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' \ + --hash=sha256:512fec6815e2dd45161054592441ef76c830eddaad55c8aa30952e6fe1ed07c0 \ + --hash=sha256:51eb9bd88391483410daad430813d982010f9c9c89512321f5b60e2cddbdddd6 \ + --hash=sha256:6c84bae345b9147082b17371e3dd5d42775bddce91f885499017f4607fdaf39f \ + --hash=sha256:700e674a166ca5778255e0e1dc4e9d79ab2acc57b9171b79e65feba7184b3370 \ + --hash=sha256:7b5b1ac819a3f946d3b2ee07f09149578ae76066d70b44df3fa990add49a82e4 \ + --hash=sha256:e047cc068570bac9866237739607d1313b9253c3051ad84738cbb095be0537b2 \ + --hash=sha256:fe94b4564e865d968414598eea1a6de60adba0c040ba4ed05ac1300de402cd42 + # via uvicorn +watchfiles==1.2.0 \ + --hash=sha256:2581a94056e55d7d0a31a823ea92bf73749c489ca2285bfdc0fbe6b2bb49d50c \ + --hash=sha256:2995c176de7692b86a2e4c58d9ec718f753150a979cb4a754e2b4ffa38e70906 \ + --hash=sha256:2cb93af48550faf1cea04c303107c8b75833de7013e57ce27d3b8d21d8d0f58c \ + --hash=sha256:2d95ddc1eb6914154253d239089900813f6a767e174b8e6a50e7fdacb7e4236c \ + --hash=sha256:41bc1199f7523b3f82843c88cbb979180c949caef0342cf90968f178e5d49b01 \ + --hash=sha256:56d8641cf834c2836922899105bd3ce3d0dfc69291d52edf0b4d0436829b34c0 \ + --hash=sha256:7571e4464cb6e434958f867f7f730b8ab0b75e3f8e5eac0499168486ab3c33a8 \ + --hash=sha256:7a2cffd17d27d2ecbb310c2b1d8174f222a5495b1a721894afa88ec11e25b898 \ + --hash=sha256:8f70d8b291ef6e88d19b1f297a6905ddb978888d9272b0d05e6f53309856bcfc \ + --hash=sha256:8fa585ede612ee9f9e91b18bebf9ba11b9ae29a4e3a0d0cf6fca3e382133f0d5 \ + --hash=sha256:bc13eb17538be00c874699dc0abe4ee2bc8d50bb1166a6b9e175ef3fd7eb8f26 \ + --hash=sha256:c995fba777f1ea992f090f9236e9284cf7a5d1a0130dd5a3d82c598cacd76838 \ + --hash=sha256:d20029a60a71a052a24c4db7673bc4de39ab89adbaccbfb5d67987c5d73f424d \ + --hash=sha256:e53a384f76b631c3ae5334ce6a52f0baa3a911eb94a4eac7f160079868b716d5 \ + --hash=sha256:f155b3a1b2a5fc89cdc70d47ee5d54e3b75e88efa34982028a35daef9ba00379 + # via uvicorn +websockets==16.1 \ + --hash=sha256:0352f5b38b40e857b6428d468fa21dbb4dd4a567d933c26d9831b4efe1b92f43 \ + --hash=sha256:0c64c024ddf7a35331b21fcddb562a039c275d2c82e8c2d12939e7da23997270 \ + --hash=sha256:299468cbe42e2b9981134c7c51d99387d8a7bf562b00183b3eec53f882846dad \ + --hash=sha256:2bd3e12cd9afbe2baedae0b1eeade8ba64329b60fe2f9abdc966bd10fd2c2ef5 \ + --hash=sha256:353f3bc6e058ac1ccab4b3588e8598837a8c04cfc8351233e6d523be675d844c \ + --hash=sha256:35f41979c8623df9bd30d949d82010a8fda5c56ff12cd8508a5b7272b6d4b53a \ + --hash=sha256:4e969170c3b08e1d8dabd990fef1fa702c4233aeaabec33f871806e444f6a0e4 \ + --hash=sha256:6852c9f653966c16109d3b6f31181fd734f7914927e3f0fa1117af7a18c9aa21 \ + --hash=sha256:70bd789afab579602968c39f21cb925466505f3edff22f0ae852bca54978a4f9 \ + --hash=sha256:a24d1f35aef07d794a16c853c688e74956c50239bec37b4f2de080056046419b \ + --hash=sha256:a58532c49a851bcb481e58c1be23b315c17fe2fbbed509d75aeea12f543d2c15 \ + --hash=sha256:b43fcfb521ac2f34ba80b7b8ea16303e4ad82dd8af667bf40839ad3a5d37b164 \ + --hash=sha256:b6aa3f7ad345cf3862c21f4fbf2ef5e14d911348476c2845e137c091fe3a3f0b \ + --hash=sha256:b9f5d83f80f4d7c4bba6d97f3755ac05850c784dce0fd2ab371c4e41172f53ff \ + --hash=sha256:c14b6634af01541e4efe2954fd8f263386f7aa6d37c01e55dd8109fd17661452 \ + --hash=sha256:c3e99757f5baafe20fc598e202ea6f5b0b265186ad38d0a17bd8beca16296955 \ + --hash=sha256:c5149dfe490ec7e5ee5dbf624c642fb725f93a5575c7f00ab594ca9eddb8dd81 \ + --hash=sha256:d0fb4b46f121eccd539353baebd1083a8767a9a351109453d1d1caecd1ba40c2 \ + --hash=sha256:ff9b000064b88787ba9f7a3cb2af2b68a658ca5aad76458a46469e7124b678a0 + # via uvicorn +winrt-runtime==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:06510db215d4f0dc45c00fbb1251c6544e91742a0ad928011db33b30677e1576 \ + --hash=sha256:14562c29a087ccad38e379e585fef333e5c94166c807bdde67b508a6261aa195 \ + --hash=sha256:762b3d972a2f7037f7db3acbaf379dd6d8f6cda505f71f66c6b425d1a1eae2f1 \ + --hash=sha256:c8dca19e12b234ae6c3dadf1a4d0761b51e708457492c13beb666556958801ea + # via + # bleak + # winrt-windows-devices-bluetooth + # winrt-windows-devices-bluetooth-advertisement + # winrt-windows-devices-bluetooth-genericattributeprofile + # winrt-windows-devices-enumeration + # winrt-windows-devices-radios + # winrt-windows-foundation + # winrt-windows-foundation-collections + # winrt-windows-storage-streams +winrt-windows-devices-bluetooth==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:18c833ec49e7076127463679e85efc59f61785ade0dc185c852586b21be1f31c \ + --hash=sha256:419fd1078c7749119f6b4bbf6be4e586e03a0ed544c03b83178f1d85f1b3d148 \ + --hash=sha256:9b6702c462b216c91e32388023a74d0f87210cef6fd5d93b7191e9427ce2faca \ + --hash=sha256:db496d2d92742006d5a052468fc355bf7bb49e795341d695c374746113d74505 + # via bleak +winrt-windows-devices-bluetooth-advertisement==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:0223852a7b7fa5c8dea3c6a93473bd783df4439b1ed938d9871f947933e574cc \ + --hash=sha256:447d19defd8982d39944642eb7ebe89e4e20259ec9734116cf88879fb2c514ff \ + --hash=sha256:901933cc40de5eb7e5f4188897c899dd0b0f577cb2c13eab1a63c7dfe89b08c4 \ + --hash=sha256:e6c66e7d4f4ca86d2c801d30efd2b9673247b59a2b4c365d9e11650303d68d89 + # via bleak +winrt-windows-devices-bluetooth-genericattributeprofile==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:8d4e131cf3d15fc5ad81c1bcde3509ac171298217381abed6bdf687f29871984 \ + --hash=sha256:cdf6ddc375e9150d040aca67f5a17c41ceaf13a63f3668f96608bc1d045dde71 \ + --hash=sha256:db05de95cd1b24a51abb69cb936a8b17e9214e015757d0b37e3a5e207ddceb3d \ + --hash=sha256:ef894d21e0a805f3e114940254636a8045335fa9de766c7022af5d127dfad557 + # via bleak +winrt-windows-devices-enumeration==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:1db22b0292b93b0688d11ad932ad1f3629d4f471310281a2fbfe187530c2c1f3 \ + --hash=sha256:2853d687803f0dd76ae1afe3648abc0453e09dff0e7eddbb84b792eddb0473ca \ + --hash=sha256:a73bc88d7f510af454f2b392985501c96f39b89fd987140708ccaec1588ceebc \ + --hash=sha256:df316899e39bfc0ffc1f3cb0f5ee54d04e1d167fbbcc1484d2d5121449a935cf + # via bleak +winrt-windows-devices-radios==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:4c28822f9251c9d547324f596b5c2581f050254ded05e5b786c650a3502744c1 \ + --hash=sha256:4dc9b9d1501846049eb79428d64ec698d6476c27a357999b78a8331072e18a0b \ + --hash=sha256:a116e552a3f38607b9be558fb2e7de9b4450d1f9080069944d74d80cdda1873e \ + --hash=sha256:c3e683ce682338a5a5ed465f735e223ba7a22f16d0bbea2d070962bc7657edbb + # via bleak +winrt-windows-foundation==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:45550c5b6c2125cde495c409633e6b1ea5aa1677724e3b95eb8140bfccbe30c9 \ + --hash=sha256:867642ccf629611733db482c4288e17b7919f743a5873450efb6d69ae09fdc2b \ + --hash=sha256:94f4661d71cb35ebc52be7af112f2eeabdfa02cb05e0243bf9d6bd2cafaa6f37 \ + --hash=sha256:ad2f1fcaa6c34672df45527d7c533731fdf65b67c4638c2b4aca949f6eec0656 + # via bleak +winrt-windows-foundation-collections==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:0eff1ad0d8d763ad17e9e7bbd0c26a62b27215016393c05b09b046d6503ae6d5 \ + --hash=sha256:15704eef3125788f846f269cf54a3d89656fa09a1dc8428b70871f717d595ad6 \ + --hash=sha256:550dfb8c82fe74d9e0728a2a16a9175cc9e34ca2b8ef758d69b2a398894b698b \ + --hash=sha256:810ad4bd11ab4a74fdbcd3ed33b597ef7c0b03af73fc9d7986c22bcf3bd24f84 + # via bleak +winrt-windows-storage-streams==3.2.1 ; sys_platform == 'win32' \ + --hash=sha256:040cb94e6fb26b0d00a00e8b88b06fadf29dfe18cf24ed6cb3e69709c3613307 \ + --hash=sha256:476f522722751eb0b571bc7802d85a82a3cae8b1cce66061e6e758f525e7b80f \ + --hash=sha256:77c1f0e004b84347b5bd705e8f0fc63be8cd29a6093be13f1d0869d0d97b7d78 \ + --hash=sha256:e4508ee135af53e4fc142876abbf4bc7c2a95edfc7d19f52b291a8499cacd6dc + # via bleak diff --git a/deploy/laboratory/retire_fixed_lab_v1.ps1 b/deploy/laboratory/retire_fixed_lab_v1.ps1 new file mode 100644 index 00000000..375f5eca --- /dev/null +++ b/deploy/laboratory/retire_fixed_lab_v1.ps1 @@ -0,0 +1,52 @@ +param( + [Parameter(Mandatory=$true)][string]$ExpectedContainerId, + [Parameter(Mandatory=$true)][string]$RuntimeRoot, + [switch]$QueueConfirmedIdle, + [switch]$Apply +) +# One-time migration; does not prune images, model assets, sources or named volumes. +# Caller first removes V1 from Core admission and verifies no active V1 jobs. +$ErrorActionPreference = 'Stop' +$name = 'ndc-observatory-installed-lab-worker-agent' +$image = 'sha256:bfdc94ae51906cf327901951f3e03e5f9d3a2d9692593f93e16170235adbcf7a' +$old = (docker inspect $name | ConvertFrom-Json)[0] +if ($LASTEXITCODE -ne 0 -or $old.Id -ne $ExpectedContainerId -or $old.Image -ne $image) { + throw 'Fixed LAB container identity changed; refusing migration' +} +$kept = @() +foreach ($current in @('ndc-mission-core-observatory-ai-agent','ndc-observatory-m49-worker-agent')) { + $c = (docker inspect $current | ConvertFrom-Json)[0] + if ($LASTEXITCODE -ne 0 -or -not $c.State.Running) { throw 'Current agent unavailable' } + $kept += @{name=$current; id=$c.Id; image=$c.Image} +} +$tasks = @(Get-ScheduledTask | Where-Object { + ($_.Actions.Arguments -join ' ') -match 'observatory-installed-labs|installed-lab-worker-agent' +}) +if ($tasks.Count -gt 0) { throw 'Separate fixed LAB launcher found; review required' } +if (-not (Test-Path -LiteralPath $RuntimeRoot -PathType Container)) { throw 'Runtime root absent' } +$record = @{ + schema_version='missioncore.fixed-lab-retirement/v1' + retired_setup='lab-v1-eomt-ddrnet-portable-v1' + name=$name; id=$old.Id; image=$old.Image + kept_agents=$kept + preserved='All model/runtime assets, images, source and result volumes' + applied=$false +} +if ($Apply) { + if (-not $QueueConfirmedIdle) { throw 'Core queue idle check required' } + $folder=Join-Path $RuntimeRoot 'retirements' + New-Item -ItemType Directory -Force -Path $folder | Out-Null + $receipt=Join-Path $folder 'fixed-lab-v1-20261108.json' + $record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $receipt -Encoding UTF8 + docker stop --time 30 $name | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Stop failed' } + docker rm $name | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Removal failed' } + foreach ($current in $kept) { + $c=(docker inspect $current.name | ConvertFrom-Json)[0] + if ($c.Id -ne $current.id -or -not $c.State.Running) { throw 'Current agent changed' } + } + $record.applied=$true + $record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $receipt -Encoding UTF8 +} +$record | ConvertTo-Json -Depth 8 -Compress diff --git a/deploy/laboratory/verify_runtime.py b/deploy/laboratory/verify_runtime.py new file mode 100644 index 00000000..1de35818 --- /dev/null +++ b/deploy/laboratory/verify_runtime.py @@ -0,0 +1,63 @@ +"""Bounded installed-runtime check; run inside the Worker container.""" + +import json +import os +import subprocess +import tempfile +from pathlib import Path + +import rerun as rr + +from k1link.compute.integrated_perception import _camera_proxy_file +from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority + + +def main(): + authority = WorkerLaboratoryAuthority.from_environment() + if authority is None: + raise RuntimeError("Worker-only verification") + ffmpeg = Path(os.environ["MISSIONCORE_LAB_FFMPEG"]) + with tempfile.TemporaryDirectory(prefix="lab-video-check-") as scratch: + root = Path(scratch) + for rate in [15, 30]: + source = root / f"source-{rate}.mp4" + subprocess.run( + [ + str(ffmpeg), + "-v", + "error", + "-f", + "lavfi", + "-i", + f"testsrc2=size=64x64:rate={rate}", + "-frames:v", + "30", + "-c:v", + "libx264", + "-threads", + "1", + str(source), + ], + check=True, + timeout=20, + ) + proxy = _camera_proxy_file(source, 3, 22, ffmpeg, root) + stamps = rr.AssetVideo(path=proxy).read_frame_timestamps_nanos() + if len(stamps) != 20 or any( + abs(int(t) - i * 100_000_000) > 1_000_000 for i, t in enumerate(stamps) + ): + raise RuntimeError("Selected video frames or timestamps changed") + print( + json.dumps( + { + "input_rate": rate, + "selected_frames": len(stamps), + "playback_rate": 10, + "verified": True, + } + ) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/LAB_AND_INSTALLER_STORAGE.md b/docs/LAB_AND_INSTALLER_STORAGE.md new file mode 100644 index 00000000..55e6b65e --- /dev/null +++ b/docs/LAB_AND_INSTALLER_STORAGE.md @@ -0,0 +1,343 @@ +# LAB evidence and installation archive + +Canonical cross-chat policy: [MISSIONCOR-97 — Storage rules](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-97). +The card records the current operator/Worker boundaries and separately preserves +the 3 November distributed-storage research and its unresolved acceptance gates. + +Owner decision: 7 November 2026. Mission Core is the operator viewport. Worker +runtime owns heavy computation and evidence. The Git server owns historical +installation packages. This migration does not alter scans, accepted semantic +maps, installed plugins, observation recordings, or already published replay data. + +## LAB ownership and portability + +The evidence store is `experiments/archive-store` relative to the existing +Worker runtime volume. The installed LAB worker already mounts that volume at +`/runtime`; evidence is therefore visible as `/runtime/experiments/archive-store` +without a new container, a new service, or storage in a container writable layer. +The host drive or machine name is a deployment binding, not an artifact identity. + +The runtime descriptor `state/laboratory-storage.json` records ownership, +location, catalog identity and migration state. `PIN.json` records the explicit +exclusion from job/cache cleanup; it is an ownership marker, not an OS access-control mechanism. The installed runner mounts this archive read-only. The dedicated evidence service has narrowly scoped write mounts for explicit owner-authorized LAB deletion (see below). This is preserved evidence, not a TTL cache. Migration admission +requires room for the whole planned copy and a 40 GiB free-space reserve; the +archive admission budget is 128 GiB. Reaching it requires an explicit retention +decision, never deletion of earlier evidence. + +The store reuses `missioncore.artifact-manifest/v1` and the existing +`CentralArtifactStore` layout: + +- `objects/sha256//`: one immutable copy per distinct payload. +- `manifests/sha256//.json`: standard artifact manifests. +- `refs/laboratory-archive/.json`: stable named references. +- `catalog.json`: source groups, registered work IDs, references and totals. +- Each manifest has an `index` member mapping original relative paths to roles, + hashes, sizes and original file modes. Groups are bounded to 1,500 paths. + +Work IDs come from `config/laboratories`, including lifecycle evidence variants. +Unregistered historical groups remain explicitly historical evidence; archiving +does not promote them into accepted or runnable LAB results. + +Copying is resumable. Existing byte-identical Worker files may be reused only +after hashing, using independent copies so later writes to old job files cannot +change the archive. The publisher rereads and hashes every remote payload before +publishing the catalog. Local retirement requires this receipt and a separate +review of live consumers. A transferred byte count alone is not acceptance. + +Move the entire store (objects, manifests, refs, catalog and pin) when changing +Worker hosts. Rebind the runtime volume in the existing deployment; do not edit +file identities or bake host paths into an image. Verify after copying. The +portable reader is `k1link.laboratory.archive_store`: + +```sh +python -m k1link.laboratory.archive_store --store /runtime/experiments/archive-store catalog +python -m k1link.laboratory.archive_store --store /runtime/experiments/archive-store verify MANIFEST_ID +python -m k1link.laboratory.archive_store --store /runtime/experiments/archive-store restore-file ORIGINAL_RELATIVE_PATH NEW_DESTINATION +``` + +Historical migration command (7 November): the fixed LAB agent below was retired +on 8 November. It is not a current execution target. The archive remains owned +by the managed LAB evidence deployment; use the portable reader above and the +current volume binding in `deploy/laboratory/README.md`. The original receipt +recorded this invocation: + +```sh +docker exec ndc-observatory-installed-lab-worker-agent python3 /runtime/experiments/archive-store/tools/archive_store-HASH.py --store /runtime/experiments/archive-store catalog +``` + +Use the actual filename from the descriptor; `HASH` is not literal. The same `verify` and `restore-file` arguments apply. The store mount is read-only, so restore into an explicitly chosen writable destination such as the owning job workspace. + +Restoration is explicit and limited to one file. It verifies the index and bytes, +rejects unsafe paths, refuses to overwrite an existing destination and makes a +new copy rather than a mutable hardlink into evidence. Original POSIX names are lookup identities: literal Windows paths found inside historical Mac filenames are preserved as text and never interpreted as restore destinations. The destination parent +must already exist. Original modes are recorded; permissions are not silently +elevated during restoration. + +## Operator presentation is a separate retained product + +Owner clarification, 8 November 2026: the viewing product is a **complete +playable visual recording**: synchronized camera frames/segmentation, 3D cuboids, +point layers, trajectories and a seekable timeline. A report, screenshot or +catalog entry is not a replacement. Existing controls and viewer composition are +unchanged. No new narrative/neural reports are introduced in the UI. + +The operator composition routes the migrated legacy LAB and LiDAR APIs and +four recorded-perception endpoints to the Worker service. Those routes stream +responses with Range, ETag and their existing visualization contracts without +restoring whole compute directories. This does **not** cover every Observatory +path: the separate portable workflow still uses operator source CAS, result +staging/artifact storage and local replay packaging. The 8 November fresh audit +below records this remaining gap. Ready scenes, accepted visual recordings, +semantic maps, edits and compact recovery metadata remain legitimate products. + +The Worker owns `experiments/laboratory` under the runtime volume. This is a +managed compatibility workspace for existing readers, separate from the +immutable archive. It contains materialized evidence, current source bindings, +annotations and bounded presentation caches. `state/ownership.json` identifies +its owner and archive lineage; `state/materialization.json` and camera receipts +prove migration. Container data never lives in its writable layer. See +[`deploy/laboratory/README.md`](../deploy/laboratory/README.md). + +Missing/unreachable Worker returns an unavailable state (HTTP 503); it never +starts local computation or restores large inputs onto Core. Existing standalone +accepted recordings are retained, but the newly remote LAB routes require the +Worker connection. Do not imply that this migration provides universal offline +LAB playback. + +Supported `LaboratoryRunner` execution requires explicit Worker authority and +confines result/receipt paths to that volume. Existing installed-package dispatch +remains the executor for new packaged jobs; the compatibility service is not a +second scheduler or a training service. Arbitrary hand-written engineering +scripts are not sandboxed by this Python composition boundary: they must also be +run on Worker under the same ownership policy. + +Lifecycle rules: + +- New raw inputs, intermediate arrays, model weights and training checkpoints + stay on Worker. Core may receive only declared presentation products and small + status/provenance metadata. No opportunistic fallback or unlimited result sync. +- Source objects, accepted outputs, manual annotations, active jobs and rollback + pins are protected. Scratch has a job owner and terminal cleanup; age alone + never makes evidence disposable. +- Materialization admission is capped at 128 GiB and requires 40 GiB free. + Mutating service calls and runner admission check the 40 GiB reserve. This is + admission protection, **not a hard filesystem quota** for arbitrary scripts. +- Existing publication budgets remain enforced for generated visual products: + camera frames 256 MiB, ordinary/fusion RRD caches 1 GiB each, integrated and LAB + RRD caches 4 GiB each. Budget exhaustion refuses a new publication and preserves + already accepted data. Temporary renderer files are bounded and removed in + `finally`; container `/tmp` is limited to 512 MiB. No broad automatic eviction. +- Docker logs rotate (two 10 MiB files); existing pipeline JSONL journals rotate. + Keep only the active and one verified rollback service release when retiring + this deployment's superseded intermediate images/contexts. Never global-prune + another stack or delete shared image layers manually. +- Legacy catalogs that order results by directory mtime need their metadata + preserved during migration; copying bytes alone changes their selection. + Preserve exact source/result identities; do not substitute a newer profile for + an older sealed experiment. A historical profile mismatch remains a declared + playback limitation, not evidence of successful playback. +- Local retirement requires an immutable archive receipt, Worker verification, + live playback comparison, current local SHA-256 equality, and no active owner. + Changed/unrecognized files stay. Preserve operator storage-audit metadata and + all viewer/map/capture roots. Keep a per-file retirement receipt outside UI. + +## Installation packages + +The private repository `dctouch/MISSION_CORE_INSTALLERS` is separate from the +application source repository. The source repository does not receive private +binary payloads. Do not maintain a divergent "new PC" source branch. + +The archive uses standard Git LFS for binary segments and ordinary small Git +files for source indices, manifests and instructions. The server has release +attachments disabled; no server setting change is required. The initial archive +is a tar stream compressed with Zstandard (1 GiB window), split into 64 MiB LFS +segments. Each segment is independently downloaded and SHA-256 checked before +its pointer is published. A final manifest seals the ordered segment list and +the checksum of the full compressed stream. An absent or incomplete manifest +must never be interpreted as a complete backup. + +The tar contains one SHA-256 object per distinct regular file and a path-to-object +index, including original sizes/modes. The upload never needs a full temporary +archive on the Mac. Source files are checked against the inventory before and +during reading. Directory trees, links and working build environments are not +retired merely because their regular files were archived. + +This is a preservation format, not a finished offline installer or new product +download interface. Restore requires Git LFS, Zstandard with the declared window +limit and the archive reconstruction helper. The standard Git LFS client reuses already completed segments on retry; a failed segment may need retransmission. The initial tar stream is sequential, so restoring a late member requires reading earlier segments. This preservation snapshot is not yet a selective network package catalog. The helper verifies and restores selected original files. +Keep packages required by current install/update flows, active builds and pinned +local dependency chains until those consumers have explicit archive support. + +## Validation and evidence + +`tests/test_laboratory_archive_store.py` covers volume relocation with the source +removed, corruption, unsafe member paths and preservation of existing work. +`tests/test_artifact_gateway.py` checks the shared manifest/object transport. +Private source inventories, network receipts, catalog identities and retirement +receipts belong in the local migration report, not normal Git history. + +Archive/installer migration: `outputs/operator-storage-migration-20261107/REPORT.md`. +Worker execution/presentation cutover and verified local retirement: +`outputs/lab-worker-refactor-20261108/REPORT.md`. These are technical evidence files +outside the product UI. Their totals are separate measurements; do not add logical +file sizes and observed free-space deltas as one freed-disk figure. + +## Fresh audit and implementation — 8 November 2026 + +The [fresh audit](../outputs/storage-fresh-audit-20261108/REPORT.md) measured +approximately 90.48 GB logical checkout data and 68.62 GB free disk. The four +migrated compute roots held only 4.68 MB of audit metadata. Material remaining +channels were portable source/result copies (1.47 GB), five presentation-cache +families (5.97 GB), and two build trees (27.46 GB). These are dated measurements, +not deletion authority or current free-space telemetry. + +The subsequent [history/storage implementation](../outputs/lab-history-storage-20261108/REPORT.md) +adds Settings → Storage, 1–365 day retention (default 30), local availability, +verified pinning and a separate local-copy deletion action for supported portable +and composed AI Inference playback. Pinning retains the complete merged recording, +not a thumbnail. Deleting it keeps source/result evidence and history; reopening +rebuilds playback without rerunning models. The policy protects pins, shared files, +in-flight response leases, changed files and unknown paths. It applies only to +registered reproducible playback copies, not all LAB files on the operator. +The detailed lifecycle and exclusions are in [STORAGE_RETENTION.md](STORAGE_RETENTION.md). + +History exposes catalogued LAB independently of player support. That revealed +19 results in the pre-cleanup snapshot (five TREE, fourteen RAVNOVES00), including +15 formats without an admitted player. The owner subsequently authorized their +full removal, together with failed attempts. These snapshot counts are historical; +the verified current inventory belongs to +[cleanup acceptance](../outputs/lab-history-cleanup-20261108/REPORT.md). +A composition represents its exact jobs, not every attempt of the same setup. + +The UI acceptance used an existing 13:28.779 composed recording: pin, Play/Pause, +expanded view/Escape, unpin, local deletion, reopening and playback after rebuild +all passed. The registered copy was 465.9 MiB. This proves that local portable +path, not a universal remote stream or compatibility of every old experiment. + +Remaining architecture work: bound and retire portable source/result staging +and other intermediate families, preserving verified recovery; add other +presentation families to the replica lifecycle through explicit adapters; and +close install/build archival dependencies separately. Local playback copies and +necessary local decoding are intended operator behavior, not migration defects. +Local replay packaging currently exists; its retained inputs must have explicit +ownership and bounded lifecycle. A mandatory move of every playback-preparation +step to Worker is not established by this storage audit. Gaussian +scenes, semantic maps, manual edits and unique evidence remain protected. No +claim of complete LAB offload or a percentage of global storage completion is +made by this bounded implementation. + +## Explicit LAB destruction — owner clarification, 2026-11-08 + +The LAB trash action means permanent deletion on **Core and Worker**, including +its pinned playback copy, private output packages, admitted job scratch and +legacy archive payloads. It is not catalog-only hiding or an implicit archive. +Source recordings, Gaussian scenes, semantic maps and files shared by another +retained LAB are separate owners and survive. Small deletion receipts remain; +they do not retain a hidden playable result. + +`deletion_coordinator.py` freezes exact job/result identities, checks active +playback leases, blocks republication, requests authenticated Worker deletion, +then removes local owned bytes and only finally removes the catalog projection. +Missing Worker acknowledgement leaves an explicit failure and the history row. +A repeated request resumes the journal. The UI warns that undo is unavailable. +The separate local-copy button and TTL still preserve history and Worker data. + +`deletion_inventory.py` adapts admitted producer layouts; `data_deletion.py` +accepts opaque IDs and validated relative file inventories under deployment-bound +roots. Unrecognised result ownership is refused, not treated as an empty result. +Archive path tombstones prevent restore of deleted members; content shared with +a retained source/result remains. New producers must add ownership integration. +This is a scoped LAB lifecycle, not a universal sweep of every Worker directory. + +Current cleanup acceptance (8 November): 14 failed attempts and 16 unsupported/broken LAB results were permanently removed on Core and Worker. All 26 source recordings remain; three current result projections back three playable history rows. See [verified cleanup report](../outputs/lab-history-cleanup-20261108/REPORT.md). + + +## Full cleanup clarification — 8 November 2026 + +Three accepted AI Inference views are not the complete LAB subsystem. The +repository has 44 registered laboratory evidence definitions; the Worker archive +also preserves their component evidence, input captures, annotations and dated +qualification material. Keep these owners distinct from a user-deleted result. +Absence from the AI Inference history is not a deletion criterion. + +The full audit found presentation copies missed by the original flat-cache +adapter: nested session/result RRD sidecars and a v12 derived recording cached +under a deleted result ID. The deletion inventory now covers these exact legacy +layouts. The latter accepts only a recognized result ID, matching session ID and +`missioncore.derived-rerun-recording-cache/v12` schema; original source recordings +and non-cache files remain excluded. Supplemental receipts correct the prior +cleanup's coverage without resetting completed deletion journals. + +Audit, exact removals, protected component inventory and scope limitations: +`outputs/lab-global-cleanup-20261108/REPORT.md`. The audit is not a qualification +of every archived experiment, and no universal filesystem purge is implied. + + +## Local LAB playback clarification and UX — 8 November 2026 + +The operator downloads/restores ready visual data and plays it locally. No WebRTC +video stream from Worker is required. A registered complete recording is a valid +local product; its pin protects it from expiry. Unpin begins the configured +retention interval again. Local-copy removal/expiry preserves history and Worker +results; full LAB trash remains the explicit cross-host deletion operation. + +AI Inference now provides an active download action when the local copy is absent. +It prepares the recording without opening the viewer or rerunning inference. The +eye and pin use the same bounded, cancellable preparation coordinator. History +shows date / actual registered recording bytes (decimal MB), or zero when absent; +shared source/model dependencies are not misrepresented as this recording's size. + +The opaque viewer spinner is replaced with canonical progress and short stages: +availability check, recording preparation, recording opening. Unknown progress +stays indeterminate. The opening fraction, where available, comes from the player's +buffered timeline, not an invented timer or a claim about network byte transfer. +The existing server still has a synchronous packaging step; there is no measured +byte-level percentage for that step. Warm openings reuse the prepared recording. + +The current portable renderer restores required saved artifacts, builds the replay +on Core when absent, and serves the completed recording to the browser. Local +`.pack-*` directories use TemporaryDirectory cleanup. This is distinct from model +execution and from historical build outputs, source/result CAS and component +benchmarks, whose lifecycles must be audited separately. Missing UI rows alone do +not establish that component evidence is junk. + +Acceptance: [LAB playback UX](../outputs/lab-viewer-ux-20261108/REPORT.md). + + +## Remaining intermediate stores — 8 November 2026 + +AI Inference is closed in the accepted UI/history/playback scope. The separate +[intermediate storage review](../outputs/intermediate-storage-review-20261108/REPORT.md) +records actual Mac/Worker owners, verified duplicate bytes and remaining lifecycle +gates. Integrated/experimental models and their required environments, component +inputs and regression evidence remain protected, including files named `cache` +or `derived`. The detailed ownership/retirement policy is in +[STORAGE_RETENTION.md](STORAGE_RETENTION.md#intermediate-stores-and-protected-models--owner-clarification-2026-11-08). +That initial audit did not implement these mechanisms. The subsequent +[retirement/retention implementation](../outputs/lab-retirement-transport-20261108/REPORT.md) +added source/staging budgets, verified archive fallback and published-transfer +retirement. The 9 November follow-up replaces the fixed transport ceilings with +shared physical-disk admission and adds producer-owned source last-consumer GC; +see the current transfer lifecycle in `STORAGE_RETENTION.md`. + + +## Legacy review and package distinction — 8 November 2026 + +The monthly/default-30-day interval concerns only unpinned viewing copies on the +operator Core. Worker models, executor distributions/images, environments and +experimental configurations remain until a separate pipeline-consolidation +decision. Retiring transfer/expanded-data duplicates is a different operation; +it must not become model/runtime package garbage collection. + +The [follow-up audit](../outputs/legacy-lab-and-duplicates-20261108/REPORT.md) +traced the accepted modular UI and the then-retained fixed LAB V1 API/agent. +The later owner-authorized migration removed V1 admission and its standalone +container after verifying identical shared DDRNet/EoMT weights; models remain. +Two unused UI controllers and their exclusive test were removed. Shared portable +APIs, TGS and component evidence remain dependencies. Thirty-three duplicate data +paths were retained with independent APFS copy-on-write backing; no evidence +identity or model was removed. This is not a portable runtime requirement or an +automatic retention implementation. Published result transport now supports CAS-aware closeout with immutable +receipts and corruption checks. Source copies now retire after verified last-consumer completion, never by age. +Unknown historical copies stay protected. Models, images and experimental +environments are excluded. See `outputs/lab-source-lifecycle-20261109/REPORT.md`. diff --git a/docs/STORAGE_RETENTION.md b/docs/STORAGE_RETENTION.md index a6d7fbc8..1bd2a796 100644 --- a/docs/STORAGE_RETENTION.md +++ b/docs/STORAGE_RETENTION.md @@ -13,6 +13,7 @@ run at publication; service journal rotation runs in the owning writer. | Data | Retention and mechanism | | --- | --- | | Source, configuration, secrets, `.git`, installed dependencies and active UI | Not disposable storage. No generic age-based cleanup. | +| Rover/battery scene and environment profiles, materials/textures, camera/editor layout and battery UI | Durable configuration in `data_dir/scene-profiles/.../meta.json`, with `meta.previous.json` on replacement. No cache TTL or scratch cleanup; retain verified recovery sources. Browser records are migration inputs only. | | Imported Gaussian worlds, recordings, evidence, missions, plans, accepted maps, session map versions | Durable application data. No TTL. Deletion belongs to the owning product workflow or an explicitly reviewed archive/removal operation. | | Simulation qualifications, computation experiments/results, engineering materials | Preserve unique evidence and the exact input/configuration/result relationship. An old experiment is not a cache. Archive only with a verified destination and complete dependency inventory. | | Qualified releases and rollback artifacts | Explicit pins; retain independently of the intermediate count. Retiring a release requires removing its pin by name and recording the reason. | @@ -405,3 +406,222 @@ one-file restoration helper. That local-only audit did not delete Worker dataset subsequent explicit closeout is indexed separately at `outputs/storage-closeout-20261107/REPORT.md`; do not add the two cleanup totals without checking their distinct manifests. + + +## LAB and installer offload — 2026-11-07 + +The owner-authorized operator offload uses the existing Worker runtime volume +for preserved LAB evidence and a separate private Git LFS installation archive. +See [the ownership, portability and recovery contract](LAB_AND_INSTALLER_STORAGE.md). +This does not authorize removal of local viewer dependencies, source scans, +accepted maps, installed plugins or pinned build chains. Per-file retirement +requires a verified remote copy and a dependency review; archive transfer and +space reclamation are reported separately. + +## LAB playback copies — 2026-11-08 + +Global Settings → Storage controls the retention of registered portable AI +Inference playback copies: 1–365 days, default 30. The store is +`data_dir/lab-local-storage.json`; owned files stay in +`data_dir/observatory-portable-replay-cache`. The renderer registers only a +validated complete merged RRD and its mapping sidecar. Unknown historical files +are not adopted through directory scanning and are not automatically removed. + +Opening a supported result refreshes its last-use timestamp. Reading the catalog, +polling local availability or viewing Settings does not extend retention. Unpin +starts a full grace period. The reaper runs at service startup and then hourly; +changing policy may make unpinned copies eligible at the next sweep. Pin verifies +all registered file hashes and excludes that copy from expiration. Existing +cache publication budgets and free-space refusal still apply, including pinned +bytes; this is not a new global disk quota. + +Local-copy deletion checks file identities, in-flight response leases and shared +references. Pinned copies must be unpinned first. Changed files, symlinks and +unknown paths are preserved. Only the reproducible presentation is removed; +source/result evidence, catalog history, configurations, Gaussian scenes and +semantic edits are outside this store. Reopening rebuilds the presentation from +retained validated source/result data, without running inference again. + +Scope: portable results and composed portable runs only. Canonical/legacy replay +families, shared video caches, source/result CAS and install/build artifacts are +not silently included in this TTL. The portable source/result transport and +replay packager still require their separate Worker-only migration. A local pin +is not a new backup of the underlying evidence, nor proof that every historical +format can play offline. Existing protected source/result dependencies must stay +until that migration has a verified restoration contract. + +History now lists all catalogued LAB formats independently of player support; +job attempts are no longer collapsed by configuration. Exact job/result identity +prevents duplicate rows. The jobs API remains bounded to 500 jobs per module; +older-than-bound histories need pagination rather than unbounded loading. + +See [implementation and acceptance](../outputs/lab-history-storage-20261108/REPORT.md), +[storage ownership](LAB_AND_INSTALLER_STORAGE.md) and the prior +[fresh audit](../outputs/storage-fresh-audit-20261108/REPORT.md). + +## Permanent LAB trash is distinct from cache expiry — 2026-11-08 + +An explicit confirmed LAB trash operation deletes its admitted private payloads +from both Core and Worker and removes its history entry. A pinned local copy is +included; an active playback lease blocks deletion until closed. Source sessions, +Gaussian products, semantic edits, other LABs and their shared files survive. +No retained remote archive is required for this intentional permanent deletion. +The archive/copy-preservation prerequisites elsewhere in this document apply to +storage offload and cache retirement, not to this owner-authorized destruction. + +Worker receipt precedes local/catalog finalization. A failed or unavailable +Worker must not produce success or a hidden row. Durable IDs/receipts support +retry and block accidental republication. Keep only bounded audit metadata, not +inaccessible result payloads. HTTP callers cannot supply deletion paths. + +The separate “delete local copy” action and 1–365 day cache TTL keep LAB history +and remote results. Pin excludes that copy from TTL, not from full LAB trash. +See `src/k1link/laboratory/{data_deletion,deletion_inventory,deletion_coordinator}.py` +and `outputs/lab-history-cleanup-20261108/REPORT.md` for actual acceptance/limits. + +## Intermediate stores and protected models — owner clarification, 2026-11-08 + +The AI Inference UI/history/local-playback work is closed in its accepted scope. +The remaining audit is about transport copies, historical engineering materials +and component dependencies. It does not authorize treating the experimental +system itself as disposable run output. + +Integrated and experimental model weights, required runtimes/environments, +registered component code, shared inputs, benchmarks, annotations and meaningful +regression evidence are protected owners. `cache`, `derived`, an old release +directory or absence from AI Inference history is never sufficient deletion +evidence. Retire a model/version only after checking all module, experiment, +qualification and rollback consumers and making an explicit retirement decision. +The local LAB-copy retention interval applies only to unpinned local viewing +copies in Mission Core. It does not apply to Worker experiments, installed +executor packages/images, models, environments or experimental configurations. +Preserve old and new model/executor/configuration versions until the owner makes +a separate pipeline-consolidation decision. A transport package in the rules +below means job input/output transfer data, not an executor/model distribution. + +Every new intermediate producer must declare the owner and artifact role before +writing: source, model/runtime, scratch, transport package, accepted result, +presentation replica or engineering evidence. Bind exact input/code/model/config +identities and use volume-relative paths. Declare the family-level byte budget, +temporary peak/reservations, free-space reserve, active leases and terminal +cleanup/recovery contract. Single-file protocol maxima are not aggregate budgets. + +An acknowledged transfer is not by itself permission to remove staging. Verify +the durable target, publication/catalogue binding and every retry/outbox reader. +After their readers use the durable copy, retire only the job-owned payload and +preserve small identity/transfer/publication receipts. Failed/interrupted jobs +also need terminal closeout. Active, shared, unclassified or sole-copy data stays +protected; never infer terminal ownership from mtime or run a recursive TTL sweep. + +Historical duplicate bytes may be retired only with a protected retained copy, +hash/path restore index and a passing relevant evidence/consumer verification. +A product file matching an old audit file does not automatically protect that +product from later deletion or make the old audit layout reconstructible. Keep +decision-relevant negative results, exact configurations and useful regression +evidence; deduplicate their storage rather than discarding the knowledge. + +Current implementation after the 9 November follow-up: registered portable/composed +viewing copies and scoped build retention remain. Source/result transport now +uses shared physical-device reservations with a 2 GiB free-space reserve. The +8/4 GiB aggregate directory ceilings introduced on 8 November could reject valid +large/multicomponent jobs; they have been removed specifically from transport. +Other product cache quotas are unchanged. The protocol bounds (2 TiB input, +64 GiB result member / 256 GiB package) also remain unchanged. + +After verified archive and catalog publication, only exact result-package payload +duplicates in staging are retired. The immutable manifest and retirement receipt +remain; retries validate archive hashes and reject altered staging. A published +historical transfer can be closed against its original catalog/archive identity +without adding its old definition back to the compute allowlist. Original +publication timestamps and profile labels do not change during a retry. + +Registered source copies now have last-consumer retirement as described below. +Other overlay families, unknown historical ownership and Worker build/materialized +inputs still require their own adapters. These remaining classes are not covered +by the local viewing-copy TTL. This is not a hard filesystem quota on arbitrary +scripts, and installed executors/models are not subject to these budgets. + +Measured inventory, exact duplicate hashes, protected dependencies and ordered +acceptance gates: [intermediate storage review](../outputs/intermediate-storage-review-20261108/REPORT.md). + +The follow-up [legacy LAB and duplicate-storage audit](../outputs/legacy-lab-and-duplicates-20261108/REPORT.md) +removed two unused old UI controllers and their exclusive test after owner approval. +That earlier audit retained the fixed V1 executor. The later owner-authorized +retirement below removes its admission and agent; shared module/API paths remain. +Thirty-three verified duplicate files now share APFS copy-on-write blocks; paths, +hashes and independent file semantics are preserved. The volume free-space delta +was about 247 MB, not the 3.38 GB logical duplicate size. This one-off physical +deduplication does not implement future source/staging retention or retire any +model, executor, configuration or historical evidence. + + +## Fixed LAB retirement and transport closeout — 8 November 2026 + +The old combined EoMT+DDRNet setup is removed from current admission/runtime +registries. Its standalone Worker agent was removed using the guarded migration +`deploy/laboratory/retire_fixed_lab_v1.ps1`; modular AI and TGS agents remain. +Actual DDRNet/EoMT weight hashes and shared bindings match the modular assets; +no unique model needed migration. Model files, environments and images remain. + +The modular release builder now consumes `modular_model_assets.py` and current +module definitions, not the retired V1 promotion CLI. Frozen V1 registry fixtures +are for compatibility tests only. Old-named shared helpers remain where current +modules depend on them; filename age does not establish dead code. + +Three published transport packages have been closed with archive verification +and repeat checks. Their catalog entries, payload archives, viewing copies and +pins remain. Logical duplicate payload volume is recorded separately from actual +physical free space because earlier APFS clones share blocks. + +Evidence: [retirement and retention report](../outputs/lab-retirement-transport-20261108/REPORT.md). + + +## Source transfer lifecycle and capacity — 9 November 2026 + +`observatory/transfer_space.py` owns a small Core ledger shared by portable source +and result writers. Admission sums outstanding reservations on the target device +and checks actual filesystem free space, keeping 2 GiB free. Bytes already written +release the corresponding reservation to avoid double-counting disk usage. Locks +are held only for brief metadata updates, never across an async upload. Kernel +locks identify live reservations; after a process dies its private UUID reservation +metadata can be removed, including torn metadata, without deleting any partial +payload. Unknown filenames, symlinks and shared filesystem owners are preserved. +This is cooperative admission for these writers, not an OS quota against unrelated +programs or a prediction of a complete GPU run's output size. + +A result manifest preflights all missing payload bytes; each actual member reserves +space again before writing. Source members/archives reserve their declared size +before construction. Already complete exact copies are reusable even if no room +remains for new copies. Storage shortage returns HTTP 503 and Retry-After, which +the existing Worker transport treats as transient. No change to model selection, +executor identities, compute allowlists or model retention is involved. + +`observatory/source_transport_lifecycle.py` registers only producer-owned source +copies and their original paths/digests/lengths/session owners. The full durable +queue protects accepted/queued/claimed/running/paused/preemption/reconciliation +states, including hidden records. Pending or failed result publication also blocks +source retirement. A terminal failed compute job may release its duplicate only +when its exact source is still recoverable. A new run regenerates the same copy. +All associated session owners must finish; absence from a truncated UI list is +never used to infer liveness. + +The existing 15-second publication-maintenance loop runs a separate bounded source +collection pass (up to 8 ledger rows). Cross-process shared reader locks protect +materialization and the complete HTTP response, including Range, errors and +cancellation. A collector needs an exclusive lock and skips while any reader is +active. It verifies every original and the copy, rejects symlinks/hardlinks/changed +identities, records `retiring`, unlinks only the registered duplicate and records +`retired`. Interrupted retirement is repeatable. Camera archive bindings remain; +a missing retired payload regenerates deterministically from admitted originals, +while a present corrupted payload still fails integrity validation. + +The source ledger is a compact per-content receipt, not a second payload archive. +Unknown historical source files are not automatically adopted. A one-time audit +must prove ownership/restoration; `collect(only_paths=...)` fences deletion to the +reviewed paths and preserves even other registered copies outside the list. +Original recordings, models/executors, three accepted LABs, Gaussians and semantic +maps are outside this lifecycle. Worker source cache/build/expanded directories +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). diff --git a/experiments/perception/worker/observatory_portable/promote_installed_lab_v1_package.py b/experiments/perception/worker/observatory_portable/promote_installed_lab_v1_package.py index 84ae1110..01a65337 100644 --- a/experiments/perception/worker/observatory_portable/promote_installed_lab_v1_package.py +++ b/experiments/perception/worker/observatory_portable/promote_installed_lab_v1_package.py @@ -24,6 +24,15 @@ from k1link.observatory.installed_lab_worker_service import ( InstalledLabWorkerAssetBindings, InstalledLabWorkerCompositionError, ) +from k1link.observatory.modular_model_assets import ( + DDRNET_ASSETS as _DDRNET_ASSETS, +) +from k1link.observatory.modular_model_assets import ( + EOMT_ASSETS as _EOMT_ASSETS, +) +from k1link.observatory.modular_model_assets import ( + RUNTIME_ASSET_RELATIVE_PATHS as _RUNTIME_ASSET_RELATIVE_PATHS, +) from k1link.observatory.portable_lab_v1_executor import ( PORTABLE_LAB_V1_RELEASE_SCHEMA, PortableLabV1ReleaseAsset, @@ -65,111 +74,6 @@ ImageResolver = Callable[[str], str] _DOCKER_SOCKET: Final = Path("/var/run/docker.sock") _DOCKER_API_VERSION: Final = "v1.45" -_EOMT_ASSETS: Final = ( - ( - "eomt-environment", - "/environment", - "8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0", - 211_776_082, - ), - ( - "eomt-ffmpeg-runtime", - "/opt/ffmpeg", - "03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69", - 256_208_352, - ), - ( - "eomt-model-cache", - "/cache", - "064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c", - 2_552_355_458, - ), - ( - "eomt-python-environment", - "/opt/env", - "b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20", - 5_120_848_705, - ), - ( - "eomt-runner-bundle", - "/runner", - "0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7", - 145_141, - ), - ( - "eomt-transformers-environment", - "/opt/transformers", - "f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9", - 225_272_284, - ), - ( - "k1-valid-fov-root", - "/valid-fov", - "f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e", - 6_019, - ), -) -_DDRNET_ASSETS: Final = ( - ( - "ddrnet-checkpoint", - "/opt/nodedc/assets/ddrnet-checkpoint", - "b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6", - 259_419_077, - ), - ( - "ddrnet-goose-mapping", - "/opt/nodedc/assets/ddrnet-goose-mapping", - "88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f", - 1_427, - ), - ( - "ddrnet-goose-runner", - "/opt/nodedc/assets/ddrnet-goose-runner", - "b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1", - 32_877, - ), - ( - "vegetation-policy", - "/opt/nodedc/assets/vegetation-policy", - "b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35", - 3_022, - ), - ( - "vegetation-provider-map", - "/opt/nodedc/assets/vegetation-provider-map", - "f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352", - 2_756, - ), -) -_RUNTIME_ASSET_RELATIVE_PATHS: Final = { - "eomt-environment": "derived\\perception-e3-opencv413092-v1", - "eomt-ffmpeg-runtime": ( - "assets\\observatory-portable\\eomt-ffmpeg-runtime-frigate-8a364092b03561b9-v1" - ), - "eomt-model-cache": ("assets\\observatory-portable\\eomt-model-cache-cityscapes-large-1024-v1"), - "eomt-python-environment": "derived\\perception-p0-env-v1", - "eomt-runner-bundle": "assets\\observatory-portable\\eomt-runner-bundle-v2", - "eomt-transformers-environment": "derived\\perception-p0-transformers4576-v1", - "k1-valid-fov-root": ( - "assets\\observatory-portable\\" - "k1-valid-fov-root-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2-v1" - ), - "ddrnet-checkpoint": ( - "assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-checkpoint.pth" - ), - "ddrnet-goose-mapping": ( - "assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-goose-mapping.csv" - ), - "ddrnet-goose-runner": ( - "assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-goose-runner.py" - ), - "vegetation-policy": ( - "assets\\observatory-portable\\lab-v1-static-files-v1\\vegetation-policy.json" - ), - "vegetation-provider-map": ( - "assets\\observatory-portable\\lab-v1-static-files-v1\\vegetation-provider-map.json" - ), -} class InstalledLabV1PromotionError(RuntimeError): @@ -1005,4 +909,4 @@ def main(arguments: Sequence[str] | None = None) -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit("Fixed LAB V1 is retired; use scripts/build_modular_ai_worker_release.py") diff --git a/scripts/build_modular_ai_worker_release.py b/scripts/build_modular_ai_worker_release.py index 6465598d..eb547360 100644 --- a/scripts/build_modular_ai_worker_release.py +++ b/scripts/build_modular_ai_worker_release.py @@ -6,7 +6,6 @@ from __future__ import annotations import argparse import hashlib import json -import runpy import shutil from pathlib import Path from typing import Any, Final, cast @@ -21,6 +20,15 @@ from k1link.observatory.modular_composition import ModuleRegistry from k1link.observatory.modular_installed_package_steps import ( MODULAR_PACKAGE_CONTRACT_SCHEMA, ) +from k1link.observatory.modular_model_assets import ( + DDRNET_ASSETS as _DDRNET_ASSETS, +) +from k1link.observatory.modular_model_assets import ( + EOMT_ASSETS as _EOMT_ASSETS, +) +from k1link.observatory.modular_model_assets import ( + RUNTIME_ASSET_RELATIVE_PATHS as _RUNTIME_ASSET_RELATIVE_PATHS, +) from k1link.observatory.modular_result import MODULAR_RESULT_CONTRACT_SHA256 from k1link.observatory.portable_run_definitions import ( PORTABLE_RESULT_CONTRACT_SCHEMA, @@ -42,18 +50,6 @@ from k1link.observatory.portable_worker_runtime import ( ) from k1link.observatory.recorded_jobs import RecordedExecutorIdentity -_LEGACY_PROMOTION = runpy.run_path( - str( - Path(__file__).resolve().parents[1] - / "experiments/perception/worker/observatory_portable/promote_installed_lab_v1_package.py" - ) -) -_DDRNET_ASSETS = cast(tuple[tuple[str, str, str, int], ...], _LEGACY_PROMOTION["_DDRNET_ASSETS"]) -_EOMT_ASSETS = cast(tuple[tuple[str, str, str, int], ...], _LEGACY_PROMOTION["_EOMT_ASSETS"]) -_RUNTIME_ASSET_RELATIVE_PATHS = cast( - dict[str, str], _LEGACY_PROMOTION["_RUNTIME_ASSET_RELATIVE_PATHS"] -) - AUTHORITY: Final = { "commands_enabled": False, "actuation_allowed": False, @@ -137,7 +133,18 @@ def build( repository = Path(__file__).resolve().parents[1] base_registry_path = repository / "config" / "observatory-portable-run-definitions.json" base_document = json.loads(base_registry_path.read_text()) - base_definition = cast(dict[str, Any], base_document["definitions"][0]) + # Build from explicit current modules, never the old combined profile or row order. + by_setup = {row["setup_id"]: row for row in base_document["definitions"]} + base_definition = dict(by_setup["ai-segmentation-ddrnet-v1"]) + segmentation = [ + by_setup[key] for key in ("ai-segmentation-ddrnet-v1", "ai-segmentation-eomt-v1") + ] + base_definition["components"] = list( + {item["component_id"]: item for row in segmentation for item in row["components"]}.values() + ) + base_definition["models"] = list( + {item["release_id"]: item for row in segmentation for item in row["models"]}.values() + ) m49_definition = cast( dict[str, Any], next( diff --git a/src/k1link/cache_budget.py b/src/k1link/cache_budget.py index e3be03dc..95fd5860 100644 --- a/src/k1link/cache_budget.py +++ b/src/k1link/cache_budget.py @@ -11,9 +11,10 @@ import os import shutil import stat import threading -from collections.abc import Callable +from collections.abc import Callable, Iterator from contextlib import contextmanager from pathlib import Path +from typing import Any GiB = 1024**3 MiB = 1024**2 @@ -62,12 +63,12 @@ def cache_publication( root: Path, additional_bytes: int | Callable[[], int], *, - kind=None, - limit=None, - reserve=FREE_RESERVE, - max_files=10000, - error_type=CacheCapacityError, -): + kind: str | None = None, + limit: int | None = None, + reserve: int = FREE_RESERVE, + max_files: int = 10000, + error_type: type[Exception] = CacheCapacityError, +) -> Iterator[None]: """Lock admission through publication. Count temporary bytes already on disk. additional_bytes includes only bytes not yet in this root; a file renamed @@ -118,6 +119,6 @@ def cache_publication( os.close(fd) -def require_cache_room(root: Path, additional_bytes=0, **kwargs): +def require_cache_room(root: Path, additional_bytes: int = 0, **kwargs: Any) -> None: with cache_publication(root, additional_bytes, **kwargs): pass diff --git a/src/k1link/compute/integrated_perception.py b/src/k1link/compute/integrated_perception.py index 2011cdda..5cb5ba76 100644 --- a/src/k1link/compute/integrated_perception.py +++ b/src/k1link/compute/integrated_perception.py @@ -49,7 +49,7 @@ MAX_SCAN = 512 MAX_JSON_BYTES = 64 * 1024 * 1024 MAX_LINE_BYTES = 4 * 1024 * 1024 MAX_SOURCE_BYTES = 512 * 1024 * 1024 -OVERLAY_RENDERER_VERSION = "4" +OVERLAY_RENDERER_VERSION = "5" OVERLAY_ADMISSION_SCHEMA = "missioncore.e10-overlay-admission/v1" OVERLAY_CACHE_SCHEMA = "missioncore.e10-overlay-cache/v1" CUBOID_PRESENTATION_HOLD_NS = 500_000_000 @@ -1088,6 +1088,12 @@ def _camera_proxy_file( str(source), "-vf", frame_filter, + # Match the synthetic proxy timestamps instead of inheriting + # the source rate, which duplicates/drops selected frames. + "-r", + "10", + "-fps_mode", + "cfr", "-an", "-c:v", "libx264", diff --git a/src/k1link/laboratory/archive_store.py b/src/k1link/laboratory/archive_store.py new file mode 100644 index 00000000..a4dda19a --- /dev/null +++ b/src/k1link/laboratory/archive_store.py @@ -0,0 +1,192 @@ +"""Read and restore LAB evidence using the existing immutable artifact format. + +The store belongs to the Worker runtime volume. No host names, drive letters, +model execution, automatic downloads or deletion are part of this contract. +""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path, PurePosixPath, PureWindowsPath +from typing import Any + +from k1link.artifact_gateway import ArtifactIntegrityError, CentralArtifactStore + +INDEX_SCHEMA = "missioncore.laboratory-archive-index/v1" +CATALOG_SCHEMA = "missioncore.laboratory-archive-catalog/v1" + + +def relative_member(value: str) -> PurePosixPath: + path = PurePosixPath(value) + if not value or path.is_absolute() or ".." in path.parts or "\\" in value: + raise ArtifactIntegrityError("unsafe archived relative path") + if str(path) != value or ":" in value or "\x00" in value: + raise ArtifactIntegrityError("non-canonical archived path") + return path + + +def source_identity(value: str) -> str: + """Validate an opaque original POSIX name, never a restore destination. + + macOS evidence can contain literal Windows paths inside a filename. Keep + those names as lookup identities; never interpret their backslashes as + filesystem separators on the Worker or reconstruct them automatically. + """ + if not isinstance(value, str) or not value or len(value) > 8192 or "\x00" in value: + raise ArtifactIntegrityError("invalid archived source identity") + path = PurePosixPath(value) + windows = PureWindowsPath(value) + if (path.is_absolute() or ".." in path.parts or str(path) != value + or windows.drive or windows.root): + raise ArtifactIntegrityError("unsafe archived source identity") + return value + + +class LaboratoryArchiveStore: + def __init__(self, root: Path): + self.store = CentralArtifactStore(root) + + def catalog(self) -> dict[str, Any]: + path = self.store.root / "catalog.json" + if path.is_symlink() or path.stat().st_size > 8 * 1024 * 1024: + raise ArtifactIntegrityError("unsafe LAB archive catalog") + document = json.loads(path.read_bytes()) + if document.get("schema_version") != CATALOG_SCHEMA: + raise ArtifactIntegrityError("unsupported LAB archive catalog") + if not isinstance(document.get("groups"), list): + raise ArtifactIntegrityError("invalid LAB archive groups") + return document + + def find_file(self, relative_path: str) -> str: + requested = source_identity(relative_path) + matches = [] + for group in self.catalog()["groups"]: + prefix = str(relative_member(group["source_group"])) + if requested == prefix or requested.startswith(prefix + "/"): + identity = group["manifest_id"] + if any(row["path"] == requested for row in self.entries(identity)): + matches.append(identity) + if len(matches) != 1: + raise ArtifactIntegrityError("archive path is absent or ambiguous") + return matches[0] + + def entries(self, manifest_id: str) -> list[dict[str, Any]]: + manifest = self.store.read_manifest(manifest_id) + if manifest.artifact_type != "laboratory-evidence-archive": + raise ArtifactIntegrityError("not a LAB evidence archive") + index = manifest.member("index") + if index.byte_length > 8 * 1024 * 1024: + raise ArtifactIntegrityError("oversized LAB archive index") + source = self._verified(index.sha256, index.byte_length) + document = json.loads(source.read_bytes()) + if document.get("schema_version") != INDEX_SCHEMA: + raise ArtifactIntegrityError("unsupported LAB archive index") + rows = document.get("files") + if not isinstance(rows, list) or len(rows) > 2000: + raise ArtifactIntegrityError("invalid LAB archive member count") + paths = set() + for row in rows: + path = source_identity(row["path"]) + if path in paths: + raise ArtifactIntegrityError("duplicate archived path") + paths.add(path) + member = manifest.member(row["role"]) + if member.sha256 != row["sha256"] or member.byte_length != row["bytes"]: + raise ArtifactIntegrityError("LAB index and artifact manifest disagree") + tombstones = self.store.root / "deleted-members.json" + if tombstones.exists(): + if tombstones.is_symlink() or tombstones.stat().st_size > 8 * 1024**2: + raise ArtifactIntegrityError("invalid archive deletion receipt") + deleted = json.loads(tombstones.read_bytes()) + if deleted.get("version") != 1 or not isinstance(deleted.get("paths"), list): + raise ArtifactIntegrityError("invalid archive deletion receipt") + removed = set(deleted["paths"]) + rows = [row for row in rows if row["path"] not in removed] + return rows + + def verify(self, manifest_id: str) -> dict[str, int]: + rows = self.entries(manifest_id) + seen = set() + total = 0 + for row in rows: + if row["sha256"] not in seen: + self._verified(row["sha256"], row["bytes"]) + seen.add(row["sha256"]) + total += row["bytes"] + return {"files": len(rows), "objects": len(seen), "bytes": total} + + def restore_file(self, manifest_id: str, relative_path: str, destination: Path) -> Path: + requested = source_identity(relative_path) + rows = [row for row in self.entries(manifest_id) if row["path"] == requested] + if len(rows) != 1: + raise ArtifactIntegrityError("archived file is not uniquely registered") + row = rows[0] + source = self._verified(row["sha256"], row["bytes"]) + target = destination.expanduser().absolute() + if target.exists() or target.is_symlink(): + raise ArtifactIntegrityError("restore destination already exists") + if target.parent.resolve(strict=True) != target.parent: + raise ArtifactIntegrityError("restore destination contains a symlink") + # A restored working copy must never share an inode with immutable evidence. + created = False + try: + with target.open("xb") as out: + created = True + os.fchmod(out.fileno(), 0o600) + digest = hashlib.sha256() + with source.open("rb") as inp: + for block in iter(lambda: inp.read(1024 * 1024), b""): + out.write(block) + digest.update(block) + out.flush() + os.fsync(out.fileno()) + if digest.hexdigest() != row["sha256"]: + raise ArtifactIntegrityError("archive changed during restore") + except BaseException: + if created: + target.unlink(missing_ok=True) + raise + return target + + def _verified(self, sha: str, size: int) -> Path: + path = self.store.object_path(sha) + if path.is_symlink() or not path.is_file() or path.stat().st_size != size: + raise ArtifactIntegrityError("archive object missing or wrong size") + if path.resolve() != path.absolute(): + raise ArtifactIntegrityError("archive object has a linked ancestor") + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + if digest.hexdigest() != sha: + raise ArtifactIntegrityError("archive object checksum mismatch") + return path + + +def main() -> None: + """Explicit engineering access; never an automatic viewport download.""" + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--store", type=Path, required=True) + commands = parser.add_subparsers(dest="command", required=True) + commands.add_parser("catalog") + verify = commands.add_parser("verify") + verify.add_argument("manifest") + restore = commands.add_parser("restore-file") + restore.add_argument("relative_path") + restore.add_argument("destination", type=Path) + args = parser.parse_args() + store = LaboratoryArchiveStore(args.store) + if args.command == "catalog": + print(json.dumps(store.catalog(), ensure_ascii=False, indent=2)) + elif args.command == "verify": + print(json.dumps(store.verify(args.manifest))) + else: + identity = store.find_file(args.relative_path) + print(store.restore_file(identity, args.relative_path, args.destination)) + + +if __name__ == "__main__": + main() diff --git a/src/k1link/laboratory/data_deletion.py b/src/k1link/laboratory/data_deletion.py new file mode 100644 index 00000000..6fd4ba0f --- /dev/null +++ b/src/k1link/laboratory/data_deletion.py @@ -0,0 +1,181 @@ +"""Explicit LAB destruction, separate from local presentation-cache expiry. + +Only server-admitted ownership manifests supply paths. HTTP callers supply an +opaque owner ID. A durable receipt makes interrupted deletion retryable; shared +files survive while another registered owner refers to them. No age-based sweep. +""" +from __future__ import annotations + +import json +import os +import re +import stat +import threading +from pathlib import Path, PurePosixPath + +_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,191}\Z") +LOCK = threading.RLock() + + +class LabDeletionError(RuntimeError): + pass + + +def _identity(value: str) -> str: + if not isinstance(value, str) or not _ID.fullmatch(value): + raise LabDeletionError("Invalid LAB owner identity") + return value + + +def _read(path: Path): + if path.is_symlink() or path.stat().st_size > 32 * 1024**2: + raise LabDeletionError("Unsafe LAB ownership document") + return json.loads(path.read_bytes()) + + +def _write(path: Path, value): + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + with temporary.open("w") as stream: + json.dump(value, stream, sort_keys=True) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + + +class OwnedLabData: + """A portable storage owner, with deployment-bound roots and sealed inventories.""" + + def __init__(self, state: Path, roots: dict[str, Path]): + self.state = state.absolute() + self.roots = {key: value.absolute() for key, value in roots.items()} + if self.state.resolve() != self.state or any( + value.resolve() != value or not value.is_dir() for value in self.roots.values() + ): + raise LabDeletionError("Linked LAB storage root") + + def _path(self, entry, checked_directories=None): + name, relative = entry["root"], entry["path"] + if name not in self.roots or not isinstance(relative, str): + raise LabDeletionError("Unknown LAB storage root") + parts = PurePosixPath(relative) + if (not relative or parts.is_absolute() or ".." in parts.parts + or str(parts) != relative or "\\" in relative or ":" in relative): + raise LabDeletionError("Unsafe LAB storage member") + path = self.roots[name] / relative + if path == self.roots[name]: + raise LabDeletionError("LAB member cannot be its storage root") + checked = checked_directories if checked_directories is not None else set() + parent = self.roots[name] + for part in (None, *parts.parts[:-1]): + if part is not None: + parent = parent / part + if parent in checked: + continue + try: + mode = parent.lstat().st_mode + except FileNotFoundError: + pass + else: + if not stat.S_ISDIR(mode): + raise LabDeletionError("Linked or invalid LAB storage directory") + checked.add(parent) + try: + mode = path.lstat().st_mode + except FileNotFoundError: + pass + else: + if not stat.S_ISREG(mode): + raise LabDeletionError("LAB member must be a regular, unlinked file") + return path + + def register(self, owner_id: str, files: list[dict], *, complete: bool, refresh: bool = False): + """Internal producer/migration API, never exposed as arbitrary-path HTTP.""" + owner_id = _identity(owner_id) + if not complete: + raise LabDeletionError("Incomplete LAB ownership inventory") + with LOCK: + if (self.state / "receipts" / (owner_id + ".json")).exists(): + raise LabDeletionError("Deleted LAB identity cannot be republished") + normalized = sorted(files, key=lambda row: (row["root"], row["path"])) + checked = set() + paths = [self._path(row, checked) for row in normalized] + if len(paths) != len(set(paths)): + raise LabDeletionError("Duplicate LAB storage member") + document = {"version": 1, "owner_id": owner_id, "complete": True, + "files": normalized} + path = self.state / "owners" / (owner_id + ".json") + if path.exists() and not refresh and _read(path) != document: + raise LabDeletionError("LAB ownership changed") + _write(path, document) + + def _owner(self, owner_id): + path = self.state / "owners" / (_identity(owner_id) + ".json") + if not path.exists(): + raise LabDeletionError("LAB storage ownership is not registered; nothing removed") + document = _read(path) + if (document.get("version") != 1 or document.get("owner_id") != owner_id + or document.get("complete") is not True): + raise LabDeletionError("Invalid LAB ownership manifest") + return document + + def prepare(self, owner_ids: list[str]): + with LOCK: + ids = set(map(_identity, owner_ids)) + if not ids or len(ids) > 128: + raise LabDeletionError("Invalid LAB deletion set") + documents = {} + for key in ids: + receipt = self.state / "receipts" / (key + ".json") + if receipt.exists() and _read(receipt).get("state") == "deleted": + continue + documents[key] = self._owner(key) + shared = set() + checked = set() + for path in (self.state / "owners").glob("*.json"): + if path.stem in ids: + continue + other = self._owner(path.stem) + shared.update(self._path(row, checked) for row in other["files"]) + # Validate all members before deleting any, including shared members. + files = {self._path(row, checked) for doc in documents.values() for row in doc["files"]} + return documents, sorted(files - shared), len(files & shared) + + def delete(self, owner_ids: list[str]): + with LOCK: + # Receipts retain only identities/counts, never hidden result payloads. + completed = {} + pending = [] + for key in sorted(set(map(_identity, owner_ids))): + receipt = self.state / "receipts" / (key + ".json") + value = _read(receipt) if receipt.exists() else None + if value and value.get("state") == "deleted": + completed[key] = value + else: + pending.append(key) + if not pending: + return {"state": "deleted", "owners": sorted(completed)} + documents, paths, shared = self.prepare(pending) + for key in pending: + _write(self.state / "receipts" / (key + ".json"), + {"version": 1, "owner_id": key, "state": "deleting"}) + removed_bytes = 0 + for path in paths: + if path.exists(): + removed_bytes += path.stat().st_size + path.unlink() + # Remove only empty ancestors below the deployment root. + parent = path.parent + while parent not in self.roots.values(): + try: + parent.rmdir() + except OSError: + break + parent = parent.parent + for key in pending: + # Keep ownership until the receipt is committed, for retry after IO failure. + _write(self.state / "receipts" / (key + ".json"), + {"version": 1, "owner_id": key, "state": "deleted"}) + (self.state / "owners" / (key + ".json")).unlink(missing_ok=True) + return {"state": "deleted", "owners": sorted(set(pending) | set(completed)), + "removed_bytes": removed_bytes, "shared_files_retained": shared} diff --git a/src/k1link/laboratory/deletion_coordinator.py b/src/k1link/laboratory/deletion_coordinator.py new file mode 100644 index 00000000..5f1e4eb1 --- /dev/null +++ b/src/k1link/laboratory/deletion_coordinator.py @@ -0,0 +1,110 @@ +"""Coordinate explicit LAB deletion; never equate hiding with destruction.""" +from __future__ import annotations + +import json +import threading + +import httpx + +from k1link.laboratory.data_deletion import LabDeletionError, OwnedLabData, _identity, _write +from k1link.laboratory.deletion_inventory import inventory_local +from k1link.laboratory.local_presentations import LOCK as PRESENTATION_LOCK + + +class LabDeletionCoordinator: + def __init__(self, *, store, queue, compositions, copies, gateway): + self.store, self.queue, self.compositions = store, queue, compositions + self.copies, self.gateway = copies, gateway + self.state = store.data_dir / "lab-deletions" + self.local = OwnedLabData(self.state / "data-ownership", {"core": store.data_dir}) + self.lock = threading.RLock() + + def _plan(self, kind, identity): + if kind == "job": + job = self.queue.get(identity) + if job.state != "failed" or job.result_id is not None: + raise LabDeletionError("Удалять можно только завершённый ошибочный запуск.") + return {"owners": [identity], "sessions": [], "jobs": [identity], "copies": []} + if kind == "composition": + run = self.compositions.get(identity) + jobs = [self.queue.get(key) for key in run.job_ids] + if any(j.state not in {"failed", "succeeded"} for j in jobs): + raise LabDeletionError("Дождитесь завершения запуска.") + other_jobs = {key for other in self.compositions.list(include_hidden=False) + if other.run_id != identity for key in other.job_ids} + exclusive = [j for j in jobs if j.job_id not in other_jobs] + sessions = [j.result_id for j in exclusive if j.result_id] + return {"owners": [j.job_id for j in exclusive] + sessions, + "sessions": sessions, "jobs": [j.job_id for j in exclusive], + "copies": [identity] + sessions} + self.store.validate_lab_projection(identity) + binding = self.store.get_lab_instance(identity) + if binding is None: + raise LabDeletionError("Выбрана исходная запись, а не LAB.") + job_id = binding.provenance.get("job", {}).get("job_id") + if job_id and any(job_id in run.job_ids for run in + self.compositions.list(include_hidden=False)): + raise LabDeletionError("Результат входит в состав LAB. Удалите её целиком.") + if job_id and self.queue.get(job_id).state not in {"failed", "succeeded"}: + raise LabDeletionError("Дождитесь завершения запуска.") + return {"owners": [binding.result_id] + ([job_id] if job_id else []), + "sessions": [identity], "jobs": [job_id] if job_id else [], + "copies": [binding.result_id]} + + def delete(self, kind: str, identity: str): + _identity(identity) + if kind not in {"job", "lab", "composition"}: + raise LabDeletionError("Неизвестный тип LAB.") + with self.lock: + path = self.state / (kind + "-" + identity + ".json") + previous = json.loads(path.read_text()) if path.exists() else None + if previous and previous["state"] == "deleted": + return + plan = previous["plan"] if previous else self._plan(kind, identity) + local_owners = sorted(set(plan["owners"]) | set(plan["copies"])) + with PRESENTATION_LOCK: + for key in plan["copies"]: + if self.copies.leases.get(key, 0): + raise LabDeletionError("Закройте просмотр LAB перед удалением.") + for key in local_owners: + _write(self.state / "blocked" / (key + ".json"), {"deletion": identity}) + if self.gateway is None: + raise LabDeletionError("Worker недоступен. LAB остаётся в списке.") + # Missing ownership is a hard failure, never a successful catalog-only delete. + if local_owners: + if not previous: + inventory_local(self.local, local_owners) + self.local.prepare(local_owners) + _write(path, {"state": "deleting", "plan": plan}) + receipt = None + if plan["owners"]: + try: + with httpx.Client(base_url=self.gateway.base_url, + timeout=httpx.Timeout(600, connect=5), + trust_env=False, follow_redirects=False) as client: + response = client.post("/api/v1/laboratory/data-deletions", + headers={"Authorization": "Bearer " + self.gateway.token()}, + json={"owner_ids": plan["owners"]}) + response.raise_for_status() + receipt = response.json() + if (receipt.get("state") != "deleted" + or set(receipt.get("owners", [])) != set(plan["owners"])): + raise ValueError("Deletion receipt mismatch") + except (httpx.HTTPError, ValueError, OSError) as exc: + raise LabDeletionError( + "Worker не подтвердил полное удаление. " + "LAB остаётся в списке; повторите попытку." + ) from exc + with PRESENTATION_LOCK: + if local_owners: + self.local.delete(local_owners) + for key in plan["copies"]: + self.copies.remove(key, delete_lab=True) + for key in plan["sessions"]: + if self.store.get_lab_instance(key) is not None: + self.store.delete_capability_lab_projection(key) + for key in plan["jobs"]: + self.queue.hide_deleted_projection(key) + if kind == "composition": + self.compositions.delete_projection(identity) + _write(path, {"state": "deleted", "plan": plan, "worker_receipt": receipt}) diff --git a/src/k1link/laboratory/deletion_inventory.py b/src/k1link/laboratory/deletion_inventory.py new file mode 100644 index 00000000..85033d5c --- /dev/null +++ b/src/k1link/laboratory/deletion_inventory.py @@ -0,0 +1,197 @@ +"""Storage adapters for admitted LAB producers, not an arbitrary directory sweep. + +The deployment binds volume names. Each adapter derives ownership from existing +sealed result IDs, job directories, artifact manifests or replay sidecars. New +producer formats need an adapter; unknown ownership refuses deletion. +""" +from __future__ import annotations + +import re +from pathlib import Path + +from k1link.laboratory.archive_store import LaboratoryArchiveStore +from k1link.laboratory.data_deletion import LabDeletionError, OwnedLabData, _read, _write + +_JOB = re.compile(r"observatory-run-[a-f0-9]{32}\Z") +_RESULT = re.compile(r"(?:e10-integrated-perception|lab-v1-vegetation-shadow|" + r"m49-tgs-portable-review|lab-v1-eomt-ddrnet|" + r"ai-layer-(?:ddrnet|eomt|rf-detr|object-distance))-[a-f0-9]{64}\Z") + + +def _files(path: Path): + if path.is_symlink(): + raise LabDeletionError("Linked LAB directory") + if path.is_file(): + return [path] + if not path.exists(): + return [] + paths = list(path.rglob("*")) + if any(p.is_symlink() for p in paths): + raise LabDeletionError("Linked LAB member") + return [p for p in paths if p.is_file()] + + +def _add(table, key, root_name, root, paths): + table.setdefault(key, set()).update((root_name, p.relative_to(root).as_posix()) for p in paths) + + +def _replays(table, selected, root_name, root, cache): + if not cache.exists(): + return + # Current flat replay cache and legacy session/result playback caches. + # Keep depth bounded to admitted layouts; never sweep unrelated source trees. + sidecars = [*cache.glob("*.json"), *cache.glob("*/admission.json"), + *cache.glob("*/*/*.rrd.cache.json")] + for sidecar in sidecars: + if sidecar.stat().st_size > 64 * 1024: + continue + document = _read(sidecar) + key = document.get("result_id") + if key not in selected: + continue + # Both canonical overlay and complete-replay sidecars use the same stem. + if sidecar.name.endswith(".rrd.cache.json"): + payload = sidecar.with_name(sidecar.name.removesuffix(".cache.json")) + else: + payload = sidecar.with_name(sidecar.name.removesuffix(".json") + ".rrd") + files = [sidecar, payload] + _add(table, key, root_name, root, [p for p in files if p.exists()]) + + +def _register(store, selected, table): + for key in selected: + receipt = store.state / "receipts" / (key + ".json") + if receipt.exists(): + continue # Frozen inventory makes partial deletion repeatable. + if key not in table: + raise LabDeletionError("Не найден полный реестр файлов LAB; удаление отменено.") + store.register(key, [{"root": root, "path": path} + for root, path in sorted(table[key])], complete=True, refresh=True) + + + +def _shared(store, name, selected, table, references): + # Only intersecting members can protect bytes in this operation. Do not stat + # every member of an unrelated multi-year archive for each single deletion. + candidates = set().union(*table.values()) if table else set() + for key in selected: + owner = store.state / "owners" / (key + ".json") + if owner.exists(): + candidates.update((x["root"], x["path"]) for x in _read(owner)["files"]) + store.register(name, [{"root": a, "path": b} for a, b in references & candidates], + complete=True, refresh=True) + + +def inventory_local(store: OwnedLabData, selected: list[str]): + root = store.roots["core"] + selected = set(selected) + table = {key: set() for key in selected} + cas = root / "observatory-artifact-store" + kept = set() + for path in (cas / "manifests" / "sha256").glob("*/*.json"): + manifest = _read(path) + key = manifest.get("subject_id") + payloads = [cas / "objects" / "sha256" / m["sha256"][:2] / m["sha256"] + for m in manifest["members"]] + if key in selected: + _add(table, key, "core", root, [path] + payloads) + for ref in (cas / "refs").glob("*/*.json"): + if _read(ref).get("manifest_id") == path.stem: + _add(table, key, "core", root, [ref]) + else: + kept.update(("core", p.relative_to(root).as_posix()) for p in payloads) + for key in selected: + if _JOB.fullmatch(key): + _add(table, key, "core", root, + _files(root / "observatory-worker-result-staging" / key)) + profile = root / "observatory-lab-view-profiles" / (key + ".json") + if profile.exists(): + _add(table, key, "core", root, [profile]) + for name in ("observatory-portable-replay-cache", "laboratory-rerun-overlays", + "integrated-perception-overlays", "perception-overlays"): + _replays(table, selected, "core", root, root / name) + # A legacy LAB projection could cache a derived source replay under its own + # result ID. Retire only that derived product, never original recordings. + for key in selected: + if not _RESULT.fullmatch(key): + continue + folder = root / "recordings" / key + for sidecar in folder.glob("scene.operator-v12.rrd.cache.json"): + document = _read(sidecar) + if (document.get("schema_version") != "missioncore.derived-rerun-recording-cache/v12" + or document.get("session_id") != key): + raise LabDeletionError("Derived LAB recording ownership mismatch") + payload = sidecar.with_name(sidecar.name.removesuffix(".cache.json")) + _add(table, key, "core", root, [p for p in (sidecar, payload) if p.exists()]) + _shared(store, "shared-artifact-references", selected, table, kept) + _register(store, selected, table) + + +def inventory_worker(store: OwnedLabData, selected: list[str]): + selected = set(selected) + table = {key: set() for key in selected if _JOB.fullmatch(key)} + lab = store.roots.get("lab") + if lab is None: + raise LabDeletionError("LAB storage mounts are not configured") + collections = (lab / ".runtime/compute-experiments/e10/worker-results", + lab / ".runtime/compute-experiments/lab-v1-vegetation/results") + for key in selected: + for collection in collections: + path = collection / key + if _RESULT.fullmatch(key) and (path / "result.json").exists(): + if _read(path / "result.json").get("result_id") != key: + raise LabDeletionError("Result ownership mismatch") + _add(table, key, "lab", lab, _files(path)) + for name, patterns in { + "ai": ("*/jobs/{id}", "*/sources/{id}"), + "tgs": ("*/work/sources/{id}",), + }.items(): + root = store.roots.get(name) + if root is None: + raise LabDeletionError("Worker job storage mount is unavailable") + for key in selected: + if not _JOB.fullmatch(key): + continue + for pattern in patterns: + for path in root.glob(pattern.format(id=key)): + _add(table, key, name, root, _files(path)) + # Portable packages carry immutable result identity, irrespective of release directory. + for name, pattern in (("tgs", + "*/work/m49-portable/runner-output/result-packages/*/manifest.json"), + ("ai", "*/jobs/*/*/result-staging/manifest.json")): + root = store.roots[name] + for manifest in root.glob(pattern): + if manifest.stat().st_size > 1024 * 1024: + continue + doc = _read(manifest) + key = doc.get("result", {}).get("result_id") + if key in selected: + _add(table, key, name, root, _files(manifest.parent)) + for cache in (lab / "presentation").glob("*"): + if cache.is_dir(): + _replays(table, selected, "lab", lab, cache) + archive_root = store.roots.get("archive") + if archive_root is None: + raise LabDeletionError("LAB archive mount is unavailable") + archive = LaboratoryArchiveStore(archive_root) + retained = set() + retired_paths = [] + for group in archive.catalog()["groups"]: + for row in archive.entries(group["manifest_id"]): + owners = selected.intersection(Path(row["path"]).parts) + path = archive.store.object_path(row["sha256"]) + if owners: + for key in owners: + _add(table, key, "archive", archive_root, [path]) + retired_paths.append(row["path"]) + else: + retained.add(("archive", path.relative_to(archive_root).as_posix())) + _shared(store, "shared-archive-references", selected, table, retained) + _register(store, selected, table) + store.prepare(list(selected)) + # Persist just path identities before removing bytes. Restore/verify exclude these members. + # This prevents a legacy archive from resurrecting a user-deleted LAB. + tombstone = archive_root / "deleted-members.json" + previous = _read(tombstone) if tombstone.exists() else {"version": 1, "paths": []} + previous["paths"] = sorted(set(previous["paths"]) | set(retired_paths)) + _write(tombstone, previous) diff --git a/src/k1link/laboratory/execution.py b/src/k1link/laboratory/execution.py index f239e1e2..12aef538 100644 --- a/src/k1link/laboratory/execution.py +++ b/src/k1link/laboratory/execution.py @@ -28,10 +28,9 @@ from k1link.laboratory.evidence_registry import ( LaboratoryEvidenceRegistry, ) from k1link.laboratory.evidence_report import verify_laboratory_evidence_result +from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority -LABORATORY_EXECUTION_REGISTRY_SCHEMA: Final = ( - "missioncore.laboratory-execution-registry/v1" -) +LABORATORY_EXECUTION_REGISTRY_SCHEMA: Final = "missioncore.laboratory-execution-registry/v1" LABORATORY_RUN_RECEIPT_SCHEMA: Final = "missioncore.laboratory-run-receipt/v1" LABORATORY_RUN_CONTRACT: Final = "missioncore.laboratory-run/v1" @@ -76,9 +75,7 @@ class LaboratoryExecutionDefinition: _identifier(self.work_id, "work_id") if self.lifecycle not in {"canonical", "experimental"}: raise LaboratoryExecutionError("laboratory lifecycle is invalid") - expected_isolation = ( - "core-adapter" if self.lifecycle == "canonical" else "bounded-adapter" - ) + expected_isolation = "core-adapter" if self.lifecycle == "canonical" else "bounded-adapter" if self.isolation != expected_isolation: raise LaboratoryExecutionError( f"{self.lifecycle} laboratory isolation must be {expected_isolation}" @@ -234,7 +231,9 @@ class LaboratoryRunner: sink: PipelineTelemetrySink, adapters: Mapping[str, LaboratoryAdapter] | None = None, clock_ns: Callable[[], int] = time.monotonic_ns, + worker_authority: WorkerLaboratoryAuthority | None = None, ) -> None: + self._worker_authority = worker_authority or WorkerLaboratoryAuthority.from_environment() self._registry = registry self._evidence = { definition.work_id: definition for definition in evidence_registry.definitions @@ -244,6 +243,11 @@ class LaboratoryRunner: self._clock_ns = clock_ns def run(self, request: LaboratoryRunRequest) -> LaboratoryRunResult: + if self._worker_authority is None: + raise LaboratoryExecutionError( + "LAB execution requires a Worker; operator execution is disabled" + ) + self._worker_authority.admit_outputs(request.output_root, request.receipt_root) definition = self._registry.executable(request.work_id) _validate_request(request, definition) adapter = self._adapters.get(definition.adapter_id) @@ -599,11 +603,7 @@ def _publish_receipt( document_path = destination / "receipt.json" encoded = _canonical_json(receipt) + b"\n" if destination.exists(): - if ( - destination.is_symlink() - or document_path.is_symlink() - or not document_path.is_file() - ): + if destination.is_symlink() or document_path.is_symlink() or not document_path.is_file(): raise LaboratoryExecutionError("existing laboratory receipt is invalid") if document_path.read_bytes() != encoded: raise LaboratoryExecutionError("immutable laboratory receipt changed") @@ -634,9 +634,7 @@ def _definition(value: object) -> LaboratoryExecutionDefinition: contracts = _object(row["contracts"], "laboratory contracts") _exact_keys(contracts, _CONTRACT_KEYS, "laboratory contracts") input_roles = row["input_roles"] - if not isinstance(input_roles, list) or not all( - isinstance(item, str) for item in input_roles - ): + if not isinstance(input_roles, list) or not all(isinstance(item, str) for item in input_roles): raise LaboratoryExecutionError("laboratory input_roles must be strings") lifecycle = row["lifecycle"] if lifecycle not in {"canonical", "experimental"}: diff --git a/src/k1link/laboratory/execution_authority.py b/src/k1link/laboratory/execution_authority.py new file mode 100644 index 00000000..76ca6a56 --- /dev/null +++ b/src/k1link/laboratory/execution_authority.py @@ -0,0 +1,47 @@ +"""Explicit Worker execution placement for supported LAB entry points. + +This is a composition boundary, not a sandbox for arbitrary user Python code. +Operator processes have no execution authority by default. +""" + +from __future__ import annotations + +import os +import shutil +from dataclasses import dataclass +from pathlib import Path + + +class LaboratoryPlacementError(RuntimeError): + """A LAB attempted to execute outside its configured Worker runtime.""" + + +@dataclass(frozen=True) +class WorkerLaboratoryAuthority: + runtime_root: Path + free_reserve_bytes: int = 40 * 1024**3 + + @classmethod + def from_environment(cls) -> WorkerLaboratoryAuthority | None: + if os.environ.get("MISSIONCORE_LAB_RUNTIME_ROLE") != "worker": + return None + value = os.environ.get("MISSIONCORE_LAB_RUNTIME_ROOT", "") + root = Path(value) + if not value or not root.is_absolute() or root.resolve() != root or not root.is_dir(): + raise LaboratoryPlacementError("Worker LAB runtime root is unavailable") + return cls(root) + + def admit_outputs(self, *outputs: Path) -> None: + root = self.runtime_root + if not root.is_absolute() or root.resolve() != root or not root.is_dir(): + raise LaboratoryPlacementError("Worker LAB runtime root changed") + for output in outputs: + candidate = output.absolute() + if ( + candidate.resolve() != candidate + or not candidate.is_relative_to(root) + or candidate == root + ): + raise LaboratoryPlacementError("LAB output escaped the Worker runtime") + if shutil.disk_usage(root).free < self.free_reserve_bytes: + raise LaboratoryPlacementError("Worker LAB free-space reserve would be exhausted") diff --git a/src/k1link/laboratory/local_presentations.py b/src/k1link/laboratory/local_presentations.py new file mode 100644 index 00000000..eb208656 --- /dev/null +++ b/src/k1link/laboratory/local_presentations.py @@ -0,0 +1,222 @@ +"""Retention of registered, reproducible LAB playback copies, never LAB evidence. + +Only the renderer can register files. Unknown/legacy files are deliberately not +adopted by scanning a directory. Pinning protects the complete merged recording. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import threading +import time +from collections.abc import Callable +from contextlib import contextmanager +from pathlib import Path + +LOCK = threading.RLock() + + +class LocalPresentationError(ValueError): + pass + + +class LocalPresentations: + def __init__(self, data_dir: Path, *, clock: Callable[[], float] = time.time): + self.root = data_dir / "observatory-portable-replay-cache" + self.index = data_dir / "lab-local-storage.json" + self.clock = clock + self.leases: dict[str, int] = {} + + def _read(self): + if not self.index.exists(): + return {"version": 1, "retention_days": 30, "entries": {}} + if self.index.is_symlink() or self.index.stat().st_size > 8 * 1024**2: + raise LocalPresentationError("Индекс локальных копий повреждён.") + data = json.loads(self.index.read_text()) + if data.get("version") != 1 or not isinstance(data.get("entries"), dict): + raise LocalPresentationError("Неизвестный формат индекса локальных копий.") + return data + + def _write(self, data): + self.index.parent.mkdir(parents=True, exist_ok=True) + temporary = self.index.with_suffix(".tmp") + with temporary.open("w") as stream: + json.dump(data, stream, sort_keys=True) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(temporary, 0o600) + os.replace(temporary, self.index) + + def _path(self, name): + if not isinstance(name, str) or not re.fullmatch( + r"[a-f0-9]{64}(?:\.replay\.rrd|\.json)", name + ): + raise LocalPresentationError("Некорректный путь локальной копии.") + path = self.root / name + if self.root.resolve() != self.root.absolute() or path.is_symlink(): + raise LocalPresentationError("Небезопасный путь локальной копии; файл сохранён.") + return path + + def _exists(self, entry): + try: + return bool(entry["files"]) and all( + self._path(f["name"]).is_file() + and self._path(f["name"]).stat().st_size == f["bytes"] + for f in entry["files"] + ) + except (OSError, KeyError, LocalPresentationError): + return False + + def register(self, result_id: str, artifact, sidecar: Path): + """Called only after renderer validation; no paths come from HTTP input.""" + with LOCK: + self._require_not_deleted(result_id) + data = self._read() + previous = data["entries"].get(result_id, {}) + if previous.get("pinned") and previous.get("sha256") != artifact.sha256: + raise LocalPresentationError( + "Закреплена другая версия просмотра. Сначала открепите её." + ) + files = [] + for path, digest in ((artifact.path, artifact.sha256), (sidecar, None)): + if path.parent != self.root or self._path(path.name) != path: + raise LocalPresentationError("Файл не принадлежит кэшу просмотра.") + if digest is None: + digest = hashlib.sha256(path.read_bytes()).hexdigest() + files.append({"name": path.name, "sha256": digest, "bytes": path.stat().st_size}) + now = self.clock() + # Persist access at most once per minute during range requests. + if ( + previous.get("sha256") == artifact.sha256 + and now - previous.get("last_used", 0) < 60 + ): + return + data["entries"][result_id] = { + "files": files, + "sha256": artifact.sha256, + "bytes": artifact.byte_length, + "last_used": now, + "pinned": bool(previous.get("pinned")), + } + self._write(data) + + def snapshot(self): + with LOCK: + data = self._read() + return { + "retention_days": data["retention_days"], + "entries": { + key: { + "local": self._exists(value), + "pinned": value["pinned"], + "bytes": value["bytes"], + "last_used": value["last_used"], + } + for key, value in data["entries"].items() + }, + } + + def policy(self, days: int): + if type(days) is not int or not 1 <= days <= 365: + raise LocalPresentationError("Срок хранения — от 1 до 365 дней.") + with LOCK: + data = self._read() + data["retention_days"] = days + self._write(data) + return self.snapshot() + + def pin(self, result_id: str, value: bool): + with LOCK: + data = self._read() + entry = data["entries"].get(result_id) + if entry is None or (value and not self._exists(entry)): + raise LocalPresentationError("Сначала подготовьте полную запись просмотра.") + if value: + for file in entry["files"]: + with self._path(file["name"]).open("rb") as stream: + if hashlib.file_digest(stream, "sha256").hexdigest() != file["sha256"]: + raise LocalPresentationError( + "Локальная копия не прошла проверку целостности." + ) + entry["pinned"] = value + entry["last_used"] = self.clock() # Unpin starts a full retention interval. + self._write(data) + return self.snapshot() + + def _require_not_deleted(self, result_id: str): + if (self.index.parent / "lab-deletions" / "blocked" / (result_id + ".json")).exists(): + raise LocalPresentationError("LAB удаляется или уже удалена.") + + def acquire(self, result_id: str): + with LOCK: + self._require_not_deleted(result_id) + self.leases[result_id] = self.leases.get(result_id, 0) + 1 + + def release(self, result_id: str): + with LOCK: + self.leases[result_id] = max(0, self.leases.get(result_id, 0) - 1) + + @contextmanager + def use(self, result_id: str): + self.acquire(result_id) + try: + yield + finally: + self.release(result_id) + + def remove(self, result_id: str, *, delete_lab: bool = False): + with LOCK: + data = self._read() + entry = data["entries"].get(result_id) + if entry is None: + return self.snapshot() + if (entry["pinned"] and not delete_lab) or self.leases.get(result_id, 0): + raise LocalPresentationError("Копия закреплена или сейчас используется.") + # Validate every file before deleting any. Never erase a changed/unknown file. + paths = [] + for file in entry["files"]: + path = self._path(file["name"]) + if path.exists(): + with path.open("rb") as stream: + if hashlib.file_digest(stream, "sha256").hexdigest() != file["sha256"]: + raise LocalPresentationError( + "Копия изменилась; автоматическое удаление отменено." + ) + paths.append(path) + shared = { + file["name"] + for key, value in data["entries"].items() + if key != result_id + for file in value["files"] + } + for path in paths: + if path.name not in shared: + path.unlink() + entry["files"] = [] + entry["bytes"] = 0 + entry["sha256"] = None + if delete_lab: + del data["entries"][result_id] + self._write(data) + return self.snapshot() + + def prune(self): + with LOCK: + data = self._read() + expired = [ + key + for key, value in data["entries"].items() + if value["files"] + and not value["pinned"] + and not self.leases.get(key, 0) + and self.clock() - value["last_used"] >= data["retention_days"] * 86400 + ] + for key in expired: + try: + self.remove(key) + except (OSError, LocalPresentationError): + continue # A changed file requires inspection, never blind cleanup. + return len(expired) diff --git a/src/k1link/laboratory/materialize_archive.py b/src/k1link/laboratory/materialize_archive.py new file mode 100644 index 00000000..15fb812c --- /dev/null +++ b/src/k1link/laboratory/materialize_archive.py @@ -0,0 +1,114 @@ +"""Explicit hash-verified LAB compatibility restore on Worker, never Core.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import time +from pathlib import Path + +from k1link.artifact_gateway import ArtifactIntegrityError +from k1link.laboratory.archive_store import LaboratoryArchiveStore, relative_member + +ROOTS = { + ".runtime/compute-experiments", + ".runtime/compute-jobs", + ".runtime/compute-results", + ".runtime/worker-results", +} + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--archive", type=Path, required=True) + p.add_argument("--target", type=Path, required=True) + a = p.parse_args() + if os.environ.get("MISSIONCORE_LAB_RUNTIME_ROLE") != "worker": + raise RuntimeError("Worker only") + archive = LaboratoryArchiveStore(a.archive) + a.target.mkdir(parents=True, exist_ok=True) + if a.target.resolve() != a.target.absolute(): + raise RuntimeError("Linked target") + state = a.target / "state" + state.mkdir(exist_ok=True) + owner = state / "ownership.json" + contract = { + "schema_version": "missioncore.laboratory-runtime-volume/v1", + "owner": "mission-core-laboratory", + "role": "worker", + "budget_bytes": 128 * 1024**3, + "free_reserve_bytes": 40 * 1024**3, + "legacy_archive_catalog_sha256": hashlib.sha256( + (a.archive / "catalog.json").read_bytes() + ).hexdigest(), + } + if owner.exists() and json.loads(owner.read_text()) != contract: + raise RuntimeError("Different volume owner") + owner.write_text(json.dumps(contract, indent=2)) + rows = [] + skipped = [] + for group in archive.catalog()["groups"]: + if not any( + group["source_group"] == root or group["source_group"].startswith(root + "/") + for root in ROOTS + ): + continue + for row in archive.entries(group["manifest_id"]): + try: + relative_member(row["path"]) + except ArtifactIntegrityError: + skipped.append(row["path"]) + continue + if Path(row["path"]).name == ".DS_Store": + continue + rows.append(row) + total = sum(r["bytes"] for r in rows) + if ( + total > contract["budget_bytes"] + or shutil.disk_usage(a.target).free < total + contract["free_reserve_bytes"] + ): + raise RuntimeError("Restore budget exceeded") + started = time.time() + done = 0 + for i, row in enumerate(rows): + src = archive.store.object_path(row["sha256"]) + dst = a.target / row["path"] + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.parent.resolve() != dst.parent or dst.is_symlink(): + raise RuntimeError("Unsafe destination") + if dst.exists(): + with dst.open("rb") as f: + sha = hashlib.file_digest(f, "sha256").hexdigest() + if dst.stat().st_size != row["bytes"] or sha != row["sha256"]: + raise RuntimeError("Existing output differs: " + row["path"]) + else: + temp = dst.with_name(dst.name + ".restoring") + with src.open("rb") as inp, temp.open("wb") as out: + d = hashlib.sha256() + for block in iter(lambda: inp.read(4 * 1024**2), b""): + d.update(block) + out.write(block) + if temp.stat().st_size != row["bytes"] or d.hexdigest() != row["sha256"]: + raise RuntimeError("Archive payload differs") + os.replace(temp, dst) + done += row["bytes"] + if i % 5000 == 0: + print(json.dumps({"files": i, "bytes": done}), flush=True) + receipt = { + "schema_version": "missioncore.laboratory-materialization/v1", + "catalog_sha256": contract["legacy_archive_catalog_sha256"], + "files": len(rows), + "bytes": total, + "skipped_opaque_names": skipped, + "seconds": round(time.time() - started, 2), + "complete": True, + } + (state / "materialization.json").write_text(json.dumps(receipt, indent=2)) + print(json.dumps(receipt), flush=True) + + +if __name__ == "__main__": + main() diff --git a/src/k1link/laboratory/materialize_recorded_sources.py b/src/k1link/laboratory/materialize_recorded_sources.py new file mode 100644 index 00000000..68e42daf --- /dev/null +++ b/src/k1link/laboratory/materialize_recorded_sources.py @@ -0,0 +1,144 @@ +"""Install digest-bound LAB camera inputs from existing Worker CAS stores only.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +from pathlib import Path + +from k1link.laboratory.archive_store import relative_member +from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority +from k1link.laboratory.worker_recorded_sources import WorkerRecordedSources + + +def _digest(value: str) -> str: + if not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value): + raise ValueError("Invalid source digest") + return value + + +def _install(source: Path, target: Path, digest: str, size: int) -> None: + target.parent.mkdir(parents=True, exist_ok=True) + if target.resolve() != target.absolute() or source.resolve() != source.absolute(): + raise ValueError("Linked camera source or target") + if target.exists(): + source = target + if not source.is_file() or source.stat().st_size != size: + raise ValueError("Camera source size mismatch") + with source.open("rb") as f: + if hashlib.file_digest(f, "sha256").hexdigest() != digest: + raise ValueError("Camera source digest mismatch") + if source != target: + temporary = target.with_name(target.name + ".installing") + if temporary.is_symlink(): + raise ValueError("Linked installation temporary") + shutil.copyfile(source, temporary) + with temporary.open("rb") as f: + if hashlib.file_digest(f, "sha256").hexdigest() != digest: + raise ValueError("Camera copy digest mismatch") + os.replace(temporary, target) + + +def install( + import_path: Path, + target: Path, + archive: Path, + cache: Path, + *, + expected_bindings_sha: str | None = None, +) -> dict: + authority = WorkerLaboratoryAuthority.from_environment() + if authority is None: + raise RuntimeError("Camera materialization requires Worker execution") + authority.admit_outputs(target) + if import_path.stat().st_size > 32 * 1024**2: + raise ValueError("Oversized source import") + doc = json.loads(import_path.read_bytes()) + if doc.get("schema_version") != "missioncore.laboratory-recorded-source-import/v1": + raise ValueError("Unsupported source import") + planned = [] + for media_id, members in doc["media"].items(): + _digest(media_id) + for row in members: + rel = relative_member(row["path"]) + sha = _digest(row["sha256"]) + size = row["bytes"] + if not isinstance(size, int) or isinstance(size, bool) or not 0 < size <= 64 * 1024**2: + raise ValueError("Invalid media object size") + candidates = (archive / "objects" / "sha256" / sha[:2] / sha, cache / sha) + source = next((p for p in candidates if p.is_file()), None) + planned.append((source, target / "media" / media_id / rel, sha, size)) + missing = sum(source is None for source, *_ in planned) + if missing: + raise ValueError(f"Worker CAS lacks {missing} of {len(planned)} camera members") + total = sum(row[3] for row in planned) + if ( + total > 16 * 1024**3 + or shutil.disk_usage(authority.runtime_root).free < total + 40 * 1024**3 + ): + raise ValueError("Camera materialization budget exceeded") + for i, (source, destination, sha, size) in enumerate(planned): + _install(source, destination, sha, size) + if i % 5000 == 0: + print(json.dumps({"camera_members": i, "total": len(planned)}), flush=True) + for sha, text in doc["descriptors"].items(): + _digest(sha) + data = text.encode() + if len(data) > 16 * 1024**2 or hashlib.sha256(data).hexdigest() != sha: + raise ValueError("Invalid camera descriptor") + path = target / "descriptors" / f"{sha}.json" + path.parent.mkdir(parents=True, exist_ok=True) + if path.resolve() != path.absolute() or (path.exists() and path.read_bytes() != data): + raise ValueError("Camera descriptor conflict") + path.write_bytes(data) + sources = WorkerRecordedSources(target, bindings_document=doc["bindings"]) + for session, name in sources.bindings: + sources.manifest(session, name) + bindings = target / "bindings.json" + payload = json.dumps(doc["bindings"], sort_keys=True).encode() + if (bindings.exists() and bindings.read_bytes() != payload and ( + not expected_bindings_sha + or hashlib.sha256(bindings.read_bytes()).hexdigest() != expected_bindings_sha)): + raise ValueError("Source bindings changed since reviewed import") + temporary = bindings.with_suffix(".installing") + temporary.write_bytes(payload) + os.replace(temporary, bindings) + receipt = { + "schema_version": "missioncore.laboratory-camera-materialization/v1", + "bindings": len(sources.bindings), + "members": len(planned), + "bytes": total, + "import_sha256": hashlib.sha256(import_path.read_bytes()).hexdigest(), + "bindings_sha256": hashlib.sha256(payload).hexdigest(), + "complete": True, + } + (target / "receipt.json").write_text(json.dumps(receipt, indent=2)) + return receipt + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("import-file", "target", "archive", "cache"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--expected-bindings-sha") + a = parser.parse_args() + print( + json.dumps( + install( + a.import_file, + a.target, + a.archive, + a.cache, + expected_bindings_sha=a.expected_bindings_sha, + ) + ), + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/src/k1link/laboratory/worker_gateway.py b/src/k1link/laboratory/worker_gateway.py new file mode 100644 index 00000000..b5d84e8b --- /dev/null +++ b/src/k1link/laboratory/worker_gateway.py @@ -0,0 +1,224 @@ +"""Bounded operator transport for Worker-owned laboratory routes. + +No filesystem evidence reader, model runner, automatic retry of writes or local +compute fallback is part of this module. Responses are streamed without staging +whole datasets on the operator disk. +""" + +from __future__ import annotations + +import asyncio +import json +import re +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import urlsplit + +import httpx +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import StreamingResponse +from starlette.background import BackgroundTask + +MAX_REQUEST_BYTES = 8 * 1024 * 1024 +MAX_RESPONSE_BYTES = 2 * 1024 * 1024 * 1024 +_HEADERS = frozenset( + { + "content-type", + "content-length", + "content-range", + "accept-ranges", + "etag", + "last-modified", + "cache-control", + "content-disposition", + "content-encoding", + "x-rerun-format", + "x-uncompressed-content-length", + "x-content-type-options", + } +) +_REQUEST_HEADERS = frozenset( + { + "range", + "if-none-match", + "if-modified-since", + "if-range", + "if-match", + "content-type", + "accept", + } +) + + +@dataclass(frozen=True) +class LaboratoryGatewayConfiguration: + base_url: str + token_file: Path + + def __post_init__(self) -> None: + url = urlsplit(self.base_url) + if ( + url.scheme not in {"http", "https"} + or not url.hostname + or url.username + or url.password + or url.query + or url.fragment + or url.path not in {"", "/"} + ): + raise ValueError("Invalid LAB worker endpoint") + if url.scheme == "http" and url.hostname not in {"127.0.0.1", "::1", "localhost"}: + raise ValueError("Plain HTTP LAB transport requires a loopback SSH tunnel") + + @classmethod + def from_file(cls, path: Path) -> LaboratoryGatewayConfiguration: + if path.is_symlink() or path.stat().st_size > 8192: + raise ValueError("Invalid LAB gateway configuration") + value = json.loads(path.read_text()) + if ( + set(value) != {"schema_version", "base_url", "token_file"} + or value["schema_version"] != "missioncore.laboratory-worker-gateway/v1" + ): + raise ValueError("Unsupported LAB gateway configuration") + token_file = Path(value["token_file"]) + if not token_file.is_absolute(): + token_file = path.parent / token_file + return cls(value["base_url"], token_file) + + def token(self) -> str: + path = self.token_file + if path.is_symlink() or not path.is_file() or path.stat().st_size > 512: + raise ValueError("LAB worker credential unavailable") + token = path.read_text().strip() + if not re.fullmatch(r"[A-Za-z0-9_-]{40,256}", token): + raise ValueError("Invalid LAB worker credential") + return token + + +class LaboratoryWorkerGateway: + def __init__( + self, + configuration: LaboratoryGatewayConfiguration | None, + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self.configuration = configuration + self.transport = transport + self._capacity = asyncio.Semaphore(8) + + async def forward( + self, request: Request, path: str, *, namespace: str = "laboratory" + ) -> StreamingResponse: + if namespace not in {"laboratory", "lidar"}: + raise ValueError("Invalid Worker namespace") + if self.configuration is None: + raise HTTPException( + 503, "Worker лабораторий не настроен. Локальное выполнение отключено." + ) + # Do not let a path change the configured upstream origin or escape LAB. + if "\\" in path or any(p in {".", ".."} for p in path.split("/")): + raise HTTPException(400, "Некорректный путь LAB.") + body = bytearray() + async for part in request.stream(): + if len(body) + len(part) > MAX_REQUEST_BYTES: + raise HTTPException(413, "Запрос LAB превышает допустимый размер.") + body.extend(part) + try: + token = self.configuration.token() + except (OSError, ValueError) as exc: + raise HTTPException(503, "Подключение Worker лабораторий недоступно.") from exc + try: + await asyncio.wait_for(self._capacity.acquire(), timeout=2) + except TimeoutError: + raise HTTPException(503, "Worker лабораторий занят.") from None + client = httpx.AsyncClient( + base_url=self.configuration.base_url, + transport=self.transport, + timeout=httpx.Timeout(360 if path.endswith(".rrd") else 60, connect=5), + follow_redirects=False, + trust_env=False, + limits=httpx.Limits(max_connections=8, max_keepalive_connections=0), + ) + headers = { + k: v + for k, v in request.headers.items() + if k.lower() in _REQUEST_HEADERS or k.lower().startswith("x-m48-") + } + headers["Authorization"] = "Bearer " + token + headers["Accept-Encoding"] = "identity" + # URL construction is relative to a fixed root; query remains opaque bytes. + url = httpx.URL(self.configuration.base_url).copy_with( + path="/api/v1/" + namespace + "/" + path, + query=request.scope.get("query_string", b""), + ) + try: + response = await client.send( + client.build_request(request.method, url, headers=headers, content=bytes(body)), + stream=True, + ) + if response.headers.get("content-encoding", "identity") not in {"identity", "gzip"}: + raise ValueError("Unsupported upstream content encoding") + size = response.headers.get("content-length") + if size is not None and (not size.isdecimal() or int(size) > MAX_RESPONSE_BYTES): + raise ValueError("LAB result exceeds transfer budget") + if 300 <= response.status_code < 400 and response.status_code != 304: + raise ValueError("LAB worker redirects are not admitted") + except BaseException as exc: + await client.aclose() + self._capacity.release() + if not isinstance(exc, (httpx.HTTPError, ValueError)): + raise + raise HTTPException( + 503, "Worker лабораторий недоступен или вернул некорректный результат." + ) from None + + closed = False + + async def close() -> None: + nonlocal closed + if not closed: + closed = True + try: + await response.aclose() + await client.aclose() + finally: + self._capacity.release() + + async def stream(): + received = 0 + try: + chunks = ( + response.aiter_bytes() if response.is_stream_consumed else response.aiter_raw() + ) + async for chunk in chunks: + received += len(chunk) + if received > MAX_RESPONSE_BYTES: + raise RuntimeError("LAB response exceeded the transfer budget") + yield chunk + finally: + await close() + + return StreamingResponse( + stream(), + status_code=response.status_code, + headers={ + k: v + for k, v in response.headers.items() + if k.lower() in _HEADERS or k.lower().startswith("x-m48-") + }, + background=BackgroundTask(close), + ) + + +def build_laboratory_worker_gateway_router( + gateway: LaboratoryWorkerGateway, *, namespace: str = "laboratory" +) -> APIRouter: + if namespace not in {"laboratory", "lidar"}: + raise ValueError("Invalid Worker namespace") + router = APIRouter(prefix="/api/v1/" + namespace, tags=["laboratory"]) + + @router.api_route("/{path:path}", methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]) + async def proxy(request: Request, path: str): + return await gateway.forward(request, path, namespace=namespace) + + return router diff --git a/src/k1link/laboratory/worker_recorded_sources.py b/src/k1link/laboratory/worker_recorded_sources.py new file mode 100644 index 00000000..6a9d76d0 --- /dev/null +++ b/src/k1link/laboratory/worker_recorded_sources.py @@ -0,0 +1,89 @@ +"""Digest-bound recorded camera bindings for the Worker LAB viewer. + +Uses the same prepared-media validator and exact-fragment decoder as the +operator viewer. There is no session database copy or source download fallback. +""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from k1link.laboratory.archive_store import relative_member +from k1link.sessions.media import RecordedMediaManifest, _manifest_from_sidecar +from k1link.sessions.models import RecordedMediaArtifact, SessionIntegrityError + + +class WorkerRecordedSources: + def __init__(self, root: Path, *, bindings_document: dict | None = None): + self.root = root.resolve(strict=True) + if bindings_document is None: + path = self.root / "bindings.json" + if path.is_symlink() or path.stat().st_size > 1024**2: + raise SessionIntegrityError("Invalid Worker camera bindings") + document = json.loads(path.read_bytes()) + else: + document = bindings_document + if document.get("schema_version") != "missioncore.laboratory-recorded-source-bindings/v1": + raise SessionIntegrityError("Unsupported Worker camera bindings") + self.bindings = {} + for row in document["sources"]: + key = (row["session_id"], row["source_name"]) + if key in self.bindings: + raise SessionIntegrityError("Ambiguous Worker source") + self.bindings[key] = row + + def manifest(self, session_id: str, source_name: str) -> RecordedMediaManifest: + binding = self.bindings.get((session_id, source_name)) + if binding is None: + raise SessionIntegrityError("Camera source is not installed on Worker") + path = self.root / relative_member(binding["descriptor"]) + if path.resolve() != path or path.stat().st_size > 16 * 1024**2: + raise SessionIntegrityError("Invalid Worker camera descriptor") + payload = path.read_bytes() + if hashlib.sha256(payload).hexdigest() != binding["descriptor_sha256"]: + raise SessionIntegrityError("Worker camera descriptor changed") + doc = json.loads(payload) + source = self.root / relative_member(binding["media_root"]) + if source.resolve() != source or not source.is_dir(): + raise SessionIntegrityError("Worker camera source changed") + artifact = RecordedMediaArtifact( + session_id=session_id, + public_source_id=doc["public_source_id"], + artifact_id=doc["artifact_id"], + source_path=source, + byte_length=doc["manifest"]["byte_length"], + ) + epochs = tuple(source / f"epoch-{i + 1}" for i in range(len(doc["manifest"]["epochs"]))) + return _manifest_from_sidecar(doc, artifact, epochs) + + +class WorkerCanonicalRecordings: + """Verified ready RRDs used as LAB presentation inputs; never synthesized here.""" + + def __init__(self, root: Path): + self.root = root.resolve(strict=True) + path = self.root / "canonical-recordings.json" + self.rows = {} + if not path.is_file(): + return + if path.is_symlink() or path.stat().st_size > 1024**2: + raise SessionIntegrityError("Invalid canonical recording index") + doc = json.loads(path.read_bytes()) + if doc.get("schema_version") != "missioncore.laboratory-canonical-recordings/v1": + raise SessionIntegrityError("Unsupported canonical recording index") + for row in doc["recordings"]: + source = self.root / relative_member(row["path"]) + if source.resolve() != source or source.stat().st_size != row["bytes"]: + raise SessionIntegrityError("Canonical recording unavailable") + with source.open("rb") as stream: + if hashlib.file_digest(stream, "sha256").hexdigest() != row["sha256"]: + raise SessionIntegrityError("Canonical recording digest mismatch") + key = row["session_id"] + if key in self.rows: + raise SessionIntegrityError("Ambiguous canonical recording") + self.rows[key] = (source, row["sha256"]) + + def get(self, session_id: str) -> tuple[Path, str] | None: + return self.rows.get(session_id) diff --git a/src/k1link/laboratory/worker_server.py b/src/k1link/laboratory/worker_server.py new file mode 100644 index 00000000..5903d447 --- /dev/null +++ b/src/k1link/laboratory/worker_server.py @@ -0,0 +1,167 @@ +"""Worker-only LAB evidence API. New jobs use the installed-package executor.""" + +from __future__ import annotations + +import hmac +import json +import os +import shutil +from contextlib import asynccontextmanager +from pathlib import Path + +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict, Field + +from k1link.compute.pipeline_telemetry import JsonlPipelineTelemetrySink +from k1link.laboratory import ( + LaboratoryEvidenceRegistry, + LaboratoryExecutionRegistry, + LaboratoryRunner, +) +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.worker_gateway import LaboratoryGatewayConfiguration +from k1link.laboratory.worker_recorded_sources import ( + WorkerCanonicalRecordings, + WorkerRecordedSources, +) +from k1link.sessions.camera_frame import RecordedCameraFrameService +from k1link.sessions.media import RecordedMediaInspector +from k1link.web.lidar_api import build_lidar_router +from k1link.web.lidar_local_surface_service import K1LocalSurfaceReadService +from k1link.web.worker_laboratory_presentation import build_worker_laboratory_presentation +from k1link.web.worker_laboratory_surface import build_worker_laboratory_router + + +def create_app() -> FastAPI: + authority = WorkerLaboratoryAuthority.from_environment() + if authority is None: + raise RuntimeError("LAB server requires a configured Worker runtime") + root = authority.runtime_root + config = Path(os.environ["MISSIONCORE_LAB_CONFIGURATION_ROOT"]).resolve(strict=True) + credential = LaboratoryGatewayConfiguration( + "http://127.0.0.1", Path(os.environ["MISSIONCORE_LAB_TOKEN_FILE"]) + ) + token = credential.token() + registry = LaboratoryEvidenceRegistry.from_directory(config / "laboratories") + execution = LaboratoryExecutionRegistry.from_file( + config / "laboratory-execution.json", registry + ) + runner = LaboratoryRunner( + registry=execution, + evidence_registry=registry, + sink=JsonlPipelineTelemetrySink(root / "state" / "laboratory-runs.jsonl"), + worker_authority=authority, + ) + deletion_roots = json.loads(os.environ.get("MISSIONCORE_LAB_DELETION_ROOTS", "{}")) + owned_data = OwnedLabData(root / "state" / "data-ownership", { + name: Path(value) for name, value in deletion_roots.items() + }) + camera = None + ffmpeg = Path(os.environ.get("MISSIONCORE_LAB_FFMPEG", "/usr/bin/ffmpeg")) + if (root / "recorded-sources" / "bindings.json").is_file() and ffmpeg.is_file(): + sources = WorkerRecordedSources(root / "recorded-sources") + camera = RecordedCameraFrameService( + None, + RecordedMediaInspector(), + ffmpeg_path=ffmpeg, + cache_root=root / "presentation" / "camera-frame-cache", + manifest_provider=sources.manifest, + ) + surface_reader = K1LocalSurfaceReadService() + + @asynccontextmanager + async def lifespan(app): + yield + surface_reader.close() + + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan) + + @app.middleware("http") + async def authorize(request: Request, call_next): + if not hmac.compare_digest(request.headers.get("authorization", ""), "Bearer " + token): + 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: + 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): + return JSONResponse( + {"detail": "Worker free-space reserve reached"}, status_code=507 + ) + return await call_next(request) + + @app.get("/health") + def health(): + return { + "schema_version": "missioncore.laboratory-worker-health/v1", + "role": "worker", + "local_fallback": False, + } + + @app.post("/api/v1/laboratory/data-deletions") + def delete_owned_data(value: DataDeletionRequest): + try: + with DELETION_LOCK: + inventory_worker(owned_data, value.owner_ids) + return owned_data.delete(value.owner_ids) + except (LabDeletionError, OSError, ValueError) as exc: + raise HTTPException(409, "Не удалось полностью удалить данные LAB на Worker.") from exc + + app.include_router( + build_worker_laboratory_router( + repository_root=root, + configuration_root=config, + presentation_root=root / "presentation", + ffmpeg_path=ffmpeg if ffmpeg.is_file() else None, + camera_frame_provider=camera.extract if camera else None, + camera_playback_provider=camera.playback_source if camera else None, + evaluation_runner=runner, + canonical_recording_provider=WorkerCanonicalRecordings(root / "recorded-sources").get, + ) + ) + app.include_router( + build_lidar_router( + root_provider=lambda: ( + root / ".runtime" / "compute-experiments" / "lidar-replay-v2" / "packs" + ), + ground_root_provider=lambda: ( + root / ".runtime" / "compute-experiments" / "lidar-ground-v1" / "benchmarks" + ), + field_review_root_provider=lambda: ( + root / ".runtime" / "compute-experiments" / "lidar-field-review-v1" / "reviews" + ), + local_surface_root_provider=lambda: ( + root / ".runtime" / "compute-experiments" / "k1-local-surface-v1" / "models" + ), + e10_source_root_provider=lambda: ( + root / ".runtime" / "compute-experiments" / "e10" / "lidar-packs" + ), + dataset_admission_provider=lambda: ( + root / ".runtime" / "dataset-gateway" / "admission.json" + ), + dataset_preview_provider=lambda: root / ".runtime" / "dataset-gateway" / "preview.json", + dataset_rellis_preview_provider=lambda: ( + root / ".runtime" / "dataset-gateway" / "rellis-preview.json" + ), + dataset_rellis_admission_provider=lambda: ( + root / ".runtime" / "dataset-gateway" / "rellis-admission.json" + ), + dataset_ground_preview_provider=lambda: ( + root / ".runtime" / "dataset-gateway" / "ground-comparison.json" + ), + local_surface_read_service=surface_reader, + ) + ) + if ffmpeg.is_file(): + app.include_router(build_worker_laboratory_presentation(root, ffmpeg)) + return app + + +class DataDeletionRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + owner_ids: list[str] = Field(min_length=1, max_length=128) diff --git a/src/k1link/observatory/modular_model_assets.py b/src/k1link/observatory/modular_model_assets.py new file mode 100644 index 00000000..b21203e1 --- /dev/null +++ b/src/k1link/observatory/modular_model_assets.py @@ -0,0 +1,111 @@ +"""Pinned shared segmentation assets, independent of historical LAB orchestration.""" + +from typing import Final + +EOMT_ASSETS: Final[tuple[tuple[str, str, str, int], ...]] = ( + ( + "eomt-environment", + "/environment", + "8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0", + 211_776_082, + ), + ( + "eomt-ffmpeg-runtime", + "/opt/ffmpeg", + "03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69", + 256_208_352, + ), + ( + "eomt-model-cache", + "/cache", + "064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c", + 2_552_355_458, + ), + ( + "eomt-python-environment", + "/opt/env", + "b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20", + 5_120_848_705, + ), + ( + "eomt-runner-bundle", + "/runner", + "0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7", + 145_141, + ), + ( + "eomt-transformers-environment", + "/opt/transformers", + "f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9", + 225_272_284, + ), + ( + "k1-valid-fov-root", + "/valid-fov", + "f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e", + 6_019, + ), +) + +DDRNET_ASSETS: Final[tuple[tuple[str, str, str, int], ...]] = ( + ( + "ddrnet-checkpoint", + "/opt/nodedc/assets/ddrnet-checkpoint", + "b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6", + 259_419_077, + ), + ( + "ddrnet-goose-mapping", + "/opt/nodedc/assets/ddrnet-goose-mapping", + "88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f", + 1_427, + ), + ( + "ddrnet-goose-runner", + "/opt/nodedc/assets/ddrnet-goose-runner", + "b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1", + 32_877, + ), + ( + "vegetation-policy", + "/opt/nodedc/assets/vegetation-policy", + "b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35", + 3_022, + ), + ( + "vegetation-provider-map", + "/opt/nodedc/assets/vegetation-provider-map", + "f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352", + 2_756, + ), +) + +RUNTIME_ASSET_RELATIVE_PATHS: Final = { + "eomt-environment": "derived\\perception-e3-opencv413092-v1", + "eomt-ffmpeg-runtime": ( + "assets\\observatory-portable\\eomt-ffmpeg-runtime-frigate-8a364092b03561b9-v1" + ), + "eomt-model-cache": ("assets\\observatory-portable\\eomt-model-cache-cityscapes-large-1024-v1"), + "eomt-python-environment": "derived\\perception-p0-env-v1", + "eomt-runner-bundle": "assets\\observatory-portable\\eomt-runner-bundle-v2", + "eomt-transformers-environment": "derived\\perception-p0-transformers4576-v1", + "k1-valid-fov-root": ( + "assets\\observatory-portable\\" + "k1-valid-fov-root-b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2-v1" + ), + "ddrnet-checkpoint": ( + "assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-checkpoint.pth" + ), + "ddrnet-goose-mapping": ( + "assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-goose-mapping.csv" + ), + "ddrnet-goose-runner": ( + "assets\\observatory-portable\\lab-v1-static-files-v1\\ddrnet-goose-runner.py" + ), + "vegetation-policy": ( + "assets\\observatory-portable\\lab-v1-static-files-v1\\vegetation-policy.json" + ), + "vegetation-provider-map": ( + "assets\\observatory-portable\\lab-v1-static-files-v1\\vegetation-provider-map.json" + ), +} diff --git a/src/k1link/observatory/portable_artifact_transport.py b/src/k1link/observatory/portable_artifact_transport.py index d2658120..a2bd5092 100644 --- a/src/k1link/observatory/portable_artifact_transport.py +++ b/src/k1link/observatory/portable_artifact_transport.py @@ -53,6 +53,8 @@ from k1link.observatory.source_admission import ( PORTABLE_SPATIAL_REPLAY_METADATA_ARTIFACT_ID, PORTABLE_SPATIAL_REPLAY_METADATA_MEDIA_TYPE, ) +from k1link.observatory.source_transport_lifecycle import SourceCopy, SourceTransportLifecycle +from k1link.observatory.transfer_space import TransferReservation, TransferSpace from k1link.sessions.media import RecordedMediaInspector, RecordedMediaManifest from k1link.sessions.models import ReplayCommand from k1link.sessions.store import SessionStore @@ -67,12 +69,8 @@ PORTABLE_CAMERA_EPOCH_ARCHIVE_BINDING_SCHEMA: Final = ( "missioncore.observatory-portable-camera-epoch-archive-binding/v1" ) PORTABLE_CAMERA_EPOCH_ARCHIVE_MEDIA_TYPE: Final = "application/x-tar" -PORTABLE_CAMERA_EPOCH_ARCHIVE_ID_HEADER: Final = ( - "X-Mission-Core-Camera-Epoch-Archive-Id" -) -PORTABLE_RESULT_UPLOAD_PLAN_SCHEMA: Final = ( - "missioncore.observatory-portable-result-upload-plan/v1" -) +PORTABLE_CAMERA_EPOCH_ARCHIVE_ID_HEADER: Final = "X-Mission-Core-Camera-Epoch-Archive-Id" +PORTABLE_RESULT_UPLOAD_PLAN_SCHEMA: Final = "missioncore.observatory-portable-result-upload-plan/v1" PORTABLE_RESULT_UPLOAD_BINDING_SCHEMA: Final = ( "missioncore.observatory-portable-result-upload-binding/v1" ) @@ -145,10 +143,13 @@ class PortableSourceMember: raise ValueError("source member byte length is invalid") _media_type(self.media_type) if self.kind in {"source-bundle", "source-capability"}: - if any( - value is not None - for value in (self.artifact_id, self.camera_epoch, self.camera_sequence) - ) or self.primary: + if ( + any( + value is not None + for value in (self.artifact_id, self.camera_epoch, self.camera_sequence) + ) + or self.primary + ): raise ValueError("source document member metadata is invalid") elif self.kind in {"spatial-replay", "spatial-replay-metadata"}: if ( @@ -234,9 +235,7 @@ class PortableSourceMaterializationManifest: "source": { "session_id": self.source_session_id, "bundle_sha256": self.source_bundle_sha256, - "capability_manifest_sha256": ( - self.source_capability_manifest_sha256 - ), + "capability_manifest_sha256": (self.source_capability_manifest_sha256), }, "members": [member.as_dict() for member in self.members], "authority": dict(OBSERVATION_ONLY_AUTHORITY), @@ -260,9 +259,8 @@ class PortableCameraEpochArchive: _digest(self.source_bundle_sha256, "camera epoch archive source bundle") _session_id(self.artifact_id) _positive_int(self.camera_epoch, "camera epoch archive ordinal") - if ( - not 2 <= len(self.member_ids) <= MAX_SOURCE_MEMBERS - or len(set(self.member_ids)) != len(self.member_ids) + if not 2 <= len(self.member_ids) <= MAX_SOURCE_MEMBERS or len(set(self.member_ids)) != len( + self.member_ids ): raise ValueError("camera epoch archive members are invalid") for member_id in self.member_ids: @@ -448,6 +446,15 @@ class PortableObservatoryArtifactTransport: create=result_staging_root is None, ) + self._transfer_space = TransferSpace(data_dir / "observatory-transfer-reservations") + self.source_lifecycle = SourceTransportLifecycle( + self._source_cas, + lambda sessions: self._queue.has_source_consumers(sessions), + ) + + def collect_source_copies(self) -> dict[str, int]: + return self.source_lifecycle.collect() + def source_manifest( self, *, @@ -474,36 +481,43 @@ class PortableObservatoryArtifactTransport: claim_generation: int, claimant_id: str, ) -> tuple[PortableSourceMember, Path]: - _digest(member_id, "source member id") - job = self._authorize( - job_id=job_id, - claim_token=claim_token, - claim_generation=claim_generation, - claimant_id=claimant_id, - allowed_states=("claimed", "running"), - ) - manifest = self._resolve_source_manifest(job) - matches = tuple(member for member in manifest.members if member.member_id == member_id) - if len(matches) != 1: - raise PortableArtifactTransportUnavailableError( - "source materialization member is not admitted" + with self.source_lifecycle.reading(): + _digest(member_id, "source member id") + job = self._authorize( + job_id=job_id, + claim_token=claim_token, + claim_generation=claim_generation, + claimant_id=claimant_id, + allowed_states=("claimed", "running"), ) - member = matches[0] - assert member._source_path is not None - destination = _publish_exact_cas_member( - self._source_cas, - member._source_path, - expected_sha256=member.sha256, - expected_byte_length=member.byte_length, - ) - self._authorize( - job_id=job_id, - claim_token=claim_token, - claim_generation=claim_generation, - claimant_id=claimant_id, - allowed_states=("claimed", "running"), - ) - return member, destination + manifest = self._resolve_source_manifest(job) + matches = tuple(member for member in manifest.members if member.member_id == member_id) + if len(matches) != 1: + raise PortableArtifactTransportUnavailableError( + "source materialization member is not admitted" + ) + member = matches[0] + assert member._source_path is not None + destination = _publish_exact_cas_member( + self._source_cas, + member._source_path, + expected_sha256=member.sha256, + expected_byte_length=member.byte_length, + space=self._transfer_space, + ) + self._authorize( + job_id=job_id, + claim_token=claim_token, + claim_generation=claim_generation, + claimant_id=claimant_id, + allowed_states=("claimed", "running"), + ) + self.source_lifecycle.register( + SourceCopy(destination, member.sha256, member.byte_length), + sources=[SourceCopy(member._source_path, member.sha256, member.byte_length)], + session_id=job.source_session_id, + ) + return member, destination def materialize_camera_epoch_archive( self, @@ -515,28 +529,39 @@ class PortableObservatoryArtifactTransport: ) -> tuple[PortableCameraEpochArchive, Path]: """Publish one claim-bound deterministic tar for the admitted camera epoch.""" - job = self._authorize( - job_id=job_id, - claim_token=claim_token, - claim_generation=claim_generation, - claimant_id=claimant_id, - allowed_states=("claimed", "running"), - ) - manifest = self._resolve_source_manifest(job) - members = _ordered_camera_epoch_members(manifest.members) - archive, path = _publish_camera_epoch_archive( - self._source_cas, - job=job, - members=members, - ) - self._authorize( - job_id=job_id, - claim_token=claim_token, - claim_generation=claim_generation, - claimant_id=claimant_id, - allowed_states=("claimed", "running"), - ) - return archive, path + with self.source_lifecycle.reading(): + job = self._authorize( + job_id=job_id, + claim_token=claim_token, + claim_generation=claim_generation, + claimant_id=claimant_id, + allowed_states=("claimed", "running"), + ) + manifest = self._resolve_source_manifest(job) + members = _ordered_camera_epoch_members(manifest.members) + archive, path = _publish_camera_epoch_archive( + self._source_cas, + job=job, + members=members, + space=self._transfer_space, + ) + self._authorize( + job_id=job_id, + claim_token=claim_token, + claim_generation=claim_generation, + claimant_id=claimant_id, + allowed_states=("claimed", "running"), + ) + self.source_lifecycle.register( + SourceCopy(path, archive.sha256, archive.byte_length), + sources=[ + SourceCopy(m._source_path, m.sha256, m.byte_length) + for m in members + if m._source_path is not None + ], + session_id=job.source_session_id, + ) + return archive, path def stage_result_manifest( self, @@ -582,32 +607,62 @@ class PortableObservatoryArtifactTransport: "portable result manifest belongs to another sealed job" ) total_bytes = sum(artifact.byte_length for artifact in package.artifacts) - if ( - total_bytes > MAX_RESULT_PACKAGE_BYTES - or any( - artifact.byte_length > MAX_RESULT_MEMBER_BYTES - for artifact in package.artifacts - ) + if total_bytes > MAX_RESULT_PACKAGE_BYTES or any( + artifact.byte_length > MAX_RESULT_MEMBER_BYTES for artifact in package.artifacts ): raise PortableArtifactTransportIntegrityError( "portable result package exceeds transport bounds" ) - root = self._package_root(job, result_sha256) - _prepare_secure_root(root) - binding = _ResultUploadBinding( - job_id=job.job_id, - job_identity_sha256=job.identity_sha256, - claim_generation=job.claim_generation, - claim_token_sha256=_token_sha256(claim_token), - result_id=result_id, - result_sha256=result_sha256, - package_identity_sha256=package.identity_sha256, + existing_root = self._package_root(job, result_sha256) + if (existing_root / "manifest.json").exists() and self._binding_path( + job, result_sha256 + ).exists(): + binding, stored = self._load_result_upload(job, result_sha256, claim_token=claim_token) + existing_plan = self._result_plan(job, binding, stored) + if not existing_plan.complete: + self._transfer_space.check( + self._result_staging, + sum( + member.byte_length + for member in existing_plan.members + if not member.uploaded + ), + ) + return existing_plan + # Check the whole missing package before accepting its manifest. Actual + # writes reserve space again, shared with concurrent input transfers. + missing_bytes = sum( + a.byte_length + for a in package.artifacts + if not _matches_exact_file( + _result_artifact_path(self._package_root(job, result_sha256), a), + expected_sha256=a.sha256, + expected_byte_length=a.byte_length, + ) ) - _write_immutable_file( - self._binding_path(job, result_sha256), - canonical_json(binding.as_dict()), + self._transfer_space.check( + self._result_staging, missing_bytes + len(manifest_payload) + 4096 ) - _write_immutable_file(root / "manifest.json", manifest_payload) + with self._transfer_space.reservation( + self._result_staging, + len(manifest_payload) + 4096, + ): + root = self._package_root(job, result_sha256) + _prepare_secure_root(root) + binding = _ResultUploadBinding( + job_id=job.job_id, + job_identity_sha256=job.identity_sha256, + claim_generation=job.claim_generation, + claim_token_sha256=_token_sha256(claim_token), + result_id=result_id, + result_sha256=result_sha256, + package_identity_sha256=package.identity_sha256, + ) + _write_immutable_file( + self._binding_path(job, result_sha256), + canonical_json(binding.as_dict()), + ) + _write_immutable_file(root / "manifest.json", manifest_payload) return self._result_plan(job, binding, package) async def upload_result_member( @@ -642,57 +697,65 @@ class PortableObservatoryArtifactTransport: "portable result member is not declared by the manifest" ) _member_id, artifact = matches[0] - temporary_root = _prepare_secure_root(self._generation_root(job) / ".incoming") - temporary = temporary_root / f"upload-{secrets.token_hex(16)}" - descriptor = os.open( - temporary, - os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), - 0o600, - ) - digest = hashlib.sha256() - byte_length = 0 - try: - with os.fdopen(descriptor, "wb") as stream: - async for chunk in chunks: - if not isinstance(chunk, bytes): - raise PortableArtifactTransportIntegrityError( - "portable result upload emitted a non-byte chunk" - ) - byte_length += len(chunk) - if byte_length > artifact.byte_length: - raise PortableArtifactTransportIntegrityError( - "portable result upload exceeds its declared length" - ) - digest.update(chunk) - stream.write(chunk) - stream.flush() - os.fsync(stream.fileno()) - if ( - byte_length != artifact.byte_length - or digest.hexdigest() != artifact.sha256 - ): - raise PortableArtifactTransportIntegrityError( - "portable result upload differs from its manifest" - ) - self._authorize( - job_id=job_id, - claim_token=claim_token, - claim_generation=claim_generation, - claimant_id=claimant_id, - allowed_states=("running",), - ) - destination = _result_artifact_path( - self._package_root(job, result_sha256), artifact - ) - _publish_uploaded_file( + if _matches_exact_file( + _result_artifact_path(self._package_root(job, result_sha256), artifact), + expected_sha256=artifact.sha256, + expected_byte_length=artifact.byte_length, + ): + return self._result_plan(job, binding, package) + with self._transfer_space.reservation( + self._result_staging, + artifact.byte_length, + ) as reservation: + temporary_root = _prepare_secure_root(self._generation_root(job) / ".incoming") + temporary = temporary_root / f"upload-{secrets.token_hex(16)}" + descriptor = os.open( temporary, - destination, - expected_sha256=artifact.sha256, - expected_byte_length=artifact.byte_length, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), + 0o600, ) - finally: - with suppress(FileNotFoundError): - temporary.unlink() + digest = hashlib.sha256() + byte_length = 0 + try: + with os.fdopen(descriptor, "wb", buffering=0) as stream: + async for chunk in chunks: + if not isinstance(chunk, bytes): + raise PortableArtifactTransportIntegrityError( + "portable result upload emitted a non-byte chunk" + ) + byte_length += len(chunk) + if byte_length > artifact.byte_length: + raise PortableArtifactTransportIntegrityError( + "portable result upload exceeds its declared length" + ) + digest.update(chunk) + stream.write(chunk) + reservation.written(len(chunk)) + stream.flush() + os.fsync(stream.fileno()) + if byte_length != artifact.byte_length or digest.hexdigest() != artifact.sha256: + raise PortableArtifactTransportIntegrityError( + "portable result upload differs from its manifest" + ) + self._authorize( + job_id=job_id, + claim_token=claim_token, + claim_generation=claim_generation, + claimant_id=claimant_id, + allowed_states=("running",), + ) + destination = _result_artifact_path( + self._package_root(job, result_sha256), artifact + ) + _publish_uploaded_file( + temporary, + destination, + expected_sha256=artifact.sha256, + expected_byte_length=artifact.byte_length, + ) + finally: + with suppress(FileNotFoundError): + temporary.unlink() return self._result_plan(job, binding, package) def complete_result_upload( @@ -719,9 +782,7 @@ class PortableObservatoryArtifactTransport: ) plan = self._result_plan(job, binding, package) if not plan.complete: - raise PortableArtifactTransportUnavailableError( - "portable result package is incomplete" - ) + raise PortableArtifactTransportUnavailableError("portable result package is incomplete") receipt = PortableResultUploadReceipt( job_id=job.job_id, job_identity_sha256=job.identity_sha256, @@ -785,9 +846,7 @@ class PortableObservatoryArtifactTransport: or job.result_sha256 is None or job.terminal_claim_token_sha256 is None ): - raise PortableArtifactTransportUnavailableError( - "portable result job is not terminal" - ) + raise PortableArtifactTransportUnavailableError("portable result job is not terminal") receipt = self._read_receipt(job, job.result_sha256) if ( receipt.result_id != job.result_id @@ -827,9 +886,7 @@ class PortableObservatoryArtifactTransport: raise PortableArtifactTransportIntegrityError( "portable job RunDefinition is unavailable" ) from exc - if recorded != self._queue.resolve_definition( - job.setup_id, job.definition_sha256 - ): + if recorded != self._queue.resolve_definition(job.setup_id, job.definition_sha256): raise PortableArtifactTransportIntegrityError( "portable RunDefinition differs from the queue allowlist" ) @@ -869,15 +926,11 @@ class PortableObservatoryArtifactTransport: "portable source documents disagree with the sealed job" ) try: - detail, catalog_sha256 = ( - self._session_store.get_session_with_catalog_snapshot( - job.source_session_id - ) - ) - replay = self._session_store.prepare_replay(job.source_session_id) - recorded_media = self._session_store.list_recorded_media( + detail, catalog_sha256 = self._session_store.get_session_with_catalog_snapshot( job.source_session_id ) + replay = self._session_store.prepare_replay(job.source_session_id) + recorded_media = self._session_store.list_recorded_media(job.source_session_id) except Exception as exc: raise PortableArtifactTransportUnavailableError( "portable source session is unavailable" @@ -924,9 +977,7 @@ class PortableObservatoryArtifactTransport: claim_generation=job.claim_generation, source_session_id=job.source_session_id, source_bundle_sha256=job.source_bundle_sha256, - source_capability_manifest_sha256=( - job.source_capability_manifest_sha256 - ), + source_capability_manifest_sha256=(job.source_capability_manifest_sha256), members=tuple(sorted(members, key=lambda member: member.member_id)), ) @@ -947,9 +998,7 @@ class PortableObservatoryArtifactTransport: and getattr(item, "session_id", None) == job.source_session_id ) if len(matches) != 1: - raise PortableArtifactTransportIntegrityError( - "portable camera artifact is not unique" - ) + raise PortableArtifactTransportIntegrityError("portable camera artifact is not unique") media_artifact = matches[0] try: manifest = self._media_inspector.restore_prepared( @@ -967,11 +1016,7 @@ class PortableObservatoryArtifactTransport: return _camera_source_members(job, manifest, camera) def _generation_root(self, job: ObservatoryRecordedJob) -> Path: - return ( - self._result_staging - / job.job_id - / f"generation-{job.claim_generation}" - ) + return self._result_staging / job.job_id / f"generation-{job.claim_generation}" def _package_root(self, job: ObservatoryRecordedJob, result_sha256: str) -> Path: _digest(result_sha256, "portable result sha256") @@ -1000,9 +1045,7 @@ class PortableObservatoryArtifactTransport: or binding.claim_token_sha256 != _token_sha256(claim_token) or binding.result_sha256 != result_sha256 ): - raise PortableArtifactTransportIntegrityError( - "portable result upload binding is stale" - ) + raise PortableArtifactTransportIntegrityError("portable result upload binding is stale") manifest_path = self._package_root(job, result_sha256) / "manifest.json" try: payload = _read_exact_regular_file( @@ -1098,16 +1141,12 @@ class PortableObservatoryArtifactTransport: document.get("claim_token_sha256"), "receipt claim token" ), result_id=string(document.get("result_id"), "receipt result id"), - result_sha256=string( - document.get("result_sha256"), "receipt result sha256" - ), + result_sha256=string(document.get("result_sha256"), "receipt result sha256"), package_identity_sha256=string( document.get("package_identity_sha256"), "receipt package identity", ), - member_count=_integer( - document.get("member_count"), "receipt member count" - ), + member_count=_integer(document.get("member_count"), "receipt member count"), total_bytes=_integer(document.get("total_bytes"), "receipt total bytes"), ) except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError) as exc: @@ -1145,10 +1184,9 @@ def portable_camera_epoch_archive_id( _session_id(artifact_id) _positive_int(camera_epoch, "camera epoch archive ordinal") canonical_member_ids = tuple(member_ids) - if ( - not 2 <= len(canonical_member_ids) <= MAX_SOURCE_MEMBERS - or len(set(canonical_member_ids)) != len(canonical_member_ids) - ): + if not 2 <= len(canonical_member_ids) <= MAX_SOURCE_MEMBERS or len( + set(canonical_member_ids) + ) != len(canonical_member_ids): raise ValueError("camera epoch archive members are invalid") for member_id in canonical_member_ids: _digest(member_id, "camera epoch archive member id") @@ -1186,19 +1224,14 @@ def _ordered_camera_epoch_members( raise PortableArtifactTransportIntegrityError( "portable camera epoch identity is incomplete" ) - ordered_segments = tuple( - sorted(segments, key=lambda member: member.camera_sequence or 0) - ) + ordered_segments = tuple(sorted(segments, key=lambda member: member.camera_sequence or 0)) if tuple(member.camera_sequence for member in ordered_segments) != tuple( range(1, len(ordered_segments) + 1) ) or any( - member.artifact_id != init.artifact_id - or member.camera_epoch != init.camera_epoch + member.artifact_id != init.artifact_id or member.camera_epoch != init.camera_epoch for member in ordered_segments ): - raise PortableArtifactTransportIntegrityError( - "portable camera epoch member order changed" - ) + raise PortableArtifactTransportIntegrityError("portable camera epoch member order changed") return (init, *ordered_segments) @@ -1215,13 +1248,9 @@ def _camera_archive_relative_name(member: PortableSourceMember) -> str: def _camera_epoch_archive_byte_length( members: Sequence[PortableSourceMember], ) -> int: - content_bytes = sum( - 512 + ((member.byte_length + 511) // 512) * 512 for member in members - ) + content_bytes = sum(512 + ((member.byte_length + 511) // 512) * 512 for member in members) logical_bytes = content_bytes + 1024 - return ((logical_bytes + tarfile.RECORDSIZE - 1) // tarfile.RECORDSIZE) * ( - tarfile.RECORDSIZE - ) + return ((logical_bytes + tarfile.RECORDSIZE - 1) // tarfile.RECORDSIZE) * (tarfile.RECORDSIZE) def _camera_epoch_archive_binding_identity( @@ -1248,6 +1277,7 @@ def _load_camera_epoch_archive_binding( binding_id: str, identity: Mapping[str, object], archive_root: Path, + allow_missing: bool = False, ) -> tuple[PortableCameraEpochArchive, Path]: try: payload = _read_exact_regular_file( @@ -1293,14 +1323,10 @@ def _load_camera_epoch_archive_binding( "camera epoch archive seal is invalid" ) from exc if ( - set(archive_document) - != {"archive_id", "media_type", "byte_length", "sha256"} - or archive_document.get("media_type") - != PORTABLE_CAMERA_EPOCH_ARCHIVE_MEDIA_TYPE + set(archive_document) != {"archive_id", "media_type", "byte_length", "sha256"} + or archive_document.get("media_type") != PORTABLE_CAMERA_EPOCH_ARCHIVE_MEDIA_TYPE ): - raise PortableArtifactTransportIntegrityError( - "camera epoch archive seal changed" - ) + raise PortableArtifactTransportIntegrityError("camera epoch archive seal changed") try: member_ids_value = identity["member_ids"] if not isinstance(member_ids_value, list) or any( @@ -1334,6 +1360,8 @@ def _load_camera_epoch_archive_binding( "camera epoch archive binding is invalid" ) from exc archive_path = archive_root / result.sha256[:2] / result.sha256 + if allow_missing and not archive_path.exists() and not archive_path.is_symlink(): + return result, archive_path if not _matches_exact_file( archive_path, expected_sha256=result.sha256, @@ -1350,6 +1378,7 @@ def _publish_camera_epoch_archive( *, job: ObservatoryRecordedJob, members: Sequence[PortableSourceMember], + space: TransferSpace, ) -> tuple[PortableCameraEpochArchive, Path]: ordered = _ordered_camera_epoch_members(members) init = ordered[0] @@ -1361,63 +1390,77 @@ def _publish_camera_epoch_archive( binding_root = _prepare_secure_root(archive_root / "bindings") binding_path = binding_root / f"{binding_id}.json" if binding_path.exists(): - return _load_camera_epoch_archive_binding( + cached = _load_camera_epoch_archive_binding( binding_path, binding_id=binding_id, identity=binding_identity, archive_root=archive_root, + allow_missing=True, ) + if cached[1].exists(): + return cached for member in ordered: if member._source_path is None: raise PortableArtifactTransportIntegrityError( "portable camera archive member has no admitted source" ) - temporary = archive_root / f".tmp-{secrets.token_hex(16)}" - descriptor = os.open( - temporary, - os.O_WRONLY - | os.O_CREAT - | os.O_EXCL - | getattr(os, "O_NOFOLLOW", 0), - 0o600, - ) - try: - with os.fdopen(descriptor, "wb") as stream: - descriptor = -1 - with tarfile.open( - fileobj=stream, - mode="w", - format=tarfile.USTAR_FORMAT, - ) as archive: - for member in ordered: - info = tarfile.TarInfo(_camera_archive_relative_name(member)) - info.size = member.byte_length - info.mode = 0o600 - info.mtime = 0 - info.uid = 0 - info.gid = 0 - info.uname = "" - info.gname = "" - assert member._source_path is not None - _add_exact_camera_archive_member( - archive, - info, - member._source_path, - expected_sha256=member.sha256, - expected_byte_length=member.byte_length, - ) - stream.flush() - os.fsync(stream.fileno()) - sha256, byte_length = _hash_regular_file( + with space.reservation(root, _camera_epoch_archive_byte_length(ordered) + 16384) as reservation: + temporary = archive_root / f".tmp-{secrets.token_hex(16)}" + descriptor = os.open( temporary, - maximum_bytes=MAX_CAMERA_EPOCH_ARCHIVE_BYTES, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), + 0o600, ) - if byte_length != _camera_epoch_archive_byte_length(ordered): - raise PortableArtifactTransportIntegrityError( - "portable camera epoch archive size is not deterministic" + try: + with os.fdopen(descriptor, "wb") as stream: + descriptor = -1 + with tarfile.open( + fileobj=stream, + mode="w", + format=tarfile.USTAR_FORMAT, + ) as archive: + accounted = 0 + for member in ordered: + info = tarfile.TarInfo(_camera_archive_relative_name(member)) + info.size = member.byte_length + info.mode = 0o600 + info.mtime = 0 + info.uid = 0 + info.gid = 0 + info.uname = "" + info.gname = "" + assert member._source_path is not None + _add_exact_camera_archive_member( + archive, + info, + member._source_path, + expected_sha256=member.sha256, + expected_byte_length=member.byte_length, + ) + stream.flush() + position = stream.tell() + reservation.written(position - accounted) + accounted = position + stream.flush() + os.fsync(stream.fileno()) + sha256, byte_length = _hash_regular_file( + temporary, + maximum_bytes=MAX_CAMERA_EPOCH_ARCHIVE_BYTES, ) - result = PortableCameraEpochArchive( - archive_id=portable_camera_epoch_archive_id( + if byte_length != _camera_epoch_archive_byte_length(ordered): + raise PortableArtifactTransportIntegrityError( + "portable camera epoch archive size is not deterministic" + ) + result = PortableCameraEpochArchive( + archive_id=portable_camera_epoch_archive_id( + job_identity_sha256=job.identity_sha256, + source_bundle_sha256=job.source_bundle_sha256, + artifact_id=init.artifact_id, + camera_epoch=init.camera_epoch, + member_ids=tuple(member.member_id for member in ordered), + byte_length=byte_length, + sha256=sha256, + ), job_identity_sha256=job.identity_sha256, source_bundle_sha256=job.source_bundle_sha256, artifact_id=init.artifact_id, @@ -1425,48 +1468,38 @@ def _publish_camera_epoch_archive( member_ids=tuple(member.member_id for member in ordered), byte_length=byte_length, sha256=sha256, - ), - job_identity_sha256=job.identity_sha256, - source_bundle_sha256=job.source_bundle_sha256, - artifact_id=init.artifact_id, - camera_epoch=init.camera_epoch, - member_ids=tuple(member.member_id for member in ordered), - byte_length=byte_length, - sha256=sha256, - ) - destination_root = _prepare_secure_root( - archive_root / result.sha256[:2] - ) - destination = destination_root / result.sha256 - _publish_uploaded_file( - temporary, - destination, - expected_sha256=result.sha256, - expected_byte_length=result.byte_length, - ) - _write_immutable_file( - binding_path, - canonical_json( - { - **binding_identity, - "binding_id": binding_id, - "archive": result.as_dict(), - "authority": dict(OBSERVATION_ONLY_AUTHORITY), - } - ), - ) - return result, destination - except PortableArtifactTransportError: - raise - except (OSError, tarfile.TarError, ValueError) as exc: - raise PortableArtifactTransportUnavailableError( - "portable camera epoch archive could not be materialized" - ) from exc - finally: - if descriptor >= 0: - os.close(descriptor) - with suppress(FileNotFoundError): - temporary.unlink() + ) + destination_root = _prepare_secure_root(archive_root / result.sha256[:2]) + destination = destination_root / result.sha256 + _publish_uploaded_file( + temporary, + destination, + expected_sha256=result.sha256, + expected_byte_length=result.byte_length, + ) + _write_immutable_file( + binding_path, + canonical_json( + { + **binding_identity, + "binding_id": binding_id, + "archive": result.as_dict(), + "authority": dict(OBSERVATION_ONLY_AUTHORITY), + } + ), + ) + return result, destination + except PortableArtifactTransportError: + raise + except (OSError, tarfile.TarError, ValueError) as exc: + raise PortableArtifactTransportUnavailableError( + "portable camera epoch archive could not be materialized" + ) from exc + finally: + if descriptor >= 0: + os.close(descriptor) + with suppress(FileNotFoundError): + temporary.unlink() class _ExactArchiveSource: @@ -1587,18 +1620,14 @@ def _spatial_members( spatial = object_document(bundle.get("spatial_replay"), "portable spatial replay") rows = spatial.get("members") if not isinstance(rows, list): - raise PortableArtifactTransportIntegrityError( - "portable spatial replay members are invalid" - ) + raise PortableArtifactTransportIntegrityError("portable spatial replay members are invalid") replay_by_id = {artifact.artifact_id: artifact for artifact in replay.artifacts} if len(replay_by_id) != len(replay.artifacts): raise PortableArtifactTransportIntegrityError( "portable replay artifact identities are not unique" ) if spatial.get("primary_artifact_id") != replay.primary_artifact_id: - raise PortableArtifactTransportIntegrityError( - "portable replay primary artifact changed" - ) + raise PortableArtifactTransportIntegrityError("portable replay primary artifact changed") result: list[PortableSourceMember] = [] metadata_member_count = 0 for value in rows: @@ -1615,9 +1644,7 @@ def _spatial_members( artifact_id == PORTABLE_SPATIAL_REPLAY_METADATA_ARTIFACT_ID and artifact.media_type == PORTABLE_SPATIAL_REPLAY_METADATA_MEDIA_TYPE ) - if artifact_id == PORTABLE_SPATIAL_REPLAY_METADATA_ARTIFACT_ID and not ( - is_metadata_member - ): + if artifact_id == PORTABLE_SPATIAL_REPLAY_METADATA_ARTIFACT_ID and not (is_metadata_member): raise PortableArtifactTransportIntegrityError( "portable replay metadata media type changed after admission" ) @@ -1752,12 +1779,8 @@ def _read_source_document( try: payload = _read_exact_regular_file(path, maximum_bytes=8 * 1024 * 1024) if hashlib.sha256(payload).hexdigest() != sha256: - raise PortableArtifactTransportIntegrityError( - "portable source document digest changed" - ) - document = object_document( - json.loads(payload.decode("utf-8")), "portable source document" - ) + raise PortableArtifactTransportIntegrityError("portable source document digest changed") + document = object_document(json.loads(payload.decode("utf-8")), "portable source document") if canonical_json(document) != payload: raise PortableArtifactTransportIntegrityError( "portable source document is not canonical JSON" @@ -1839,19 +1862,13 @@ def _read_upload_binding(path: Path) -> _ResultUploadBinding: raise ValueError("upload binding schema is invalid") binding = _ResultUploadBinding( job_id=string(document.get("job_id"), "upload job id"), - job_identity_sha256=string( - document.get("job_identity_sha256"), "upload job identity" - ), - claim_generation=_integer( - document.get("claim_generation"), "upload claim generation" - ), + job_identity_sha256=string(document.get("job_identity_sha256"), "upload job identity"), + claim_generation=_integer(document.get("claim_generation"), "upload claim generation"), claim_token_sha256=string( document.get("claim_token_sha256"), "upload claim token sha256" ), result_id=string(document.get("result_id"), "upload result id"), - result_sha256=string( - document.get("result_sha256"), "upload result sha256" - ), + result_sha256=string(document.get("result_sha256"), "upload result sha256"), package_identity_sha256=string( document.get("package_identity_sha256"), "upload package identity", @@ -1870,7 +1887,9 @@ def _publish_exact_cas_member( *, expected_sha256: str, expected_byte_length: int, + space: TransferSpace | None = None, ) -> Path: + space = space or TransferSpace(root.parent / "observatory-transfer-reservations") _digest(expected_sha256, "CAS member sha256") destination_root = _prepare_secure_root(root / expected_sha256[:2]) destination = destination_root / expected_sha256 @@ -1880,23 +1899,25 @@ def _publish_exact_cas_member( expected_byte_length=expected_byte_length, ): return destination - temporary = destination_root / f".tmp-{secrets.token_hex(16)}" - _copy_exact_file( - source, - temporary, - expected_sha256=expected_sha256, - expected_byte_length=expected_byte_length, - ) - try: - _publish_uploaded_file( - temporary, - destination, - expected_sha256=expected_sha256, - expected_byte_length=expected_byte_length, - ) - finally: - with suppress(FileNotFoundError): - temporary.unlink() + with space.reservation(root, expected_byte_length) as reservation: + temporary = destination_root / f".tmp-{secrets.token_hex(16)}" + try: + _copy_exact_file( + source, + temporary, + expected_sha256=expected_sha256, + expected_byte_length=expected_byte_length, + reservation=reservation, + ) + _publish_uploaded_file( + temporary, + destination, + expected_sha256=expected_sha256, + expected_byte_length=expected_byte_length, + ) + finally: + with suppress(FileNotFoundError): + temporary.unlink() return destination @@ -1906,6 +1927,7 @@ def _copy_exact_file( *, expected_sha256: str, expected_byte_length: int, + reservation: TransferReservation, ) -> None: source_descriptor = -1 destination_descriptor = -1 @@ -1937,6 +1959,7 @@ def _copy_exact_file( while view: written = os.write(destination_descriptor, view) view = view[written:] + reservation.written(written) os.fsync(destination_descriptor) after = os.fstat(source_descriptor) stable = ( @@ -1950,11 +1973,7 @@ def _copy_exact_file( after.st_size, after.st_mtime_ns, ) - if ( - copied != expected_byte_length - or digest.hexdigest() != expected_sha256 - or not stable - ): + if copied != expected_byte_length or digest.hexdigest() != expected_sha256 or not stable: raise PortableArtifactTransportIntegrityError( "source member changed during materialization" ) @@ -2064,9 +2083,7 @@ def _prepare_secure_root(path: Path, *, create: bool = True) -> Path: "artifact transport storage is unavailable" ) from exc if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): - raise PortableArtifactTransportIntegrityError( - "artifact transport storage root is unsafe" - ) + raise PortableArtifactTransportIntegrityError("artifact transport storage root is unsafe") return resolved @@ -2074,11 +2091,7 @@ def _read_exact_regular_file(path: Path, *, maximum_bytes: int) -> bytes: descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) try: before = os.fstat(descriptor) - if ( - not stat.S_ISREG(before.st_mode) - or before.st_size < 0 - or before.st_size > maximum_bytes - ): + if not stat.S_ISREG(before.st_mode) or before.st_size < 0 or before.st_size > maximum_bytes: raise PortableArtifactTransportIntegrityError( "artifact transport file is outside bounds" ) @@ -2112,11 +2125,7 @@ def _hash_regular_file(path: Path, *, maximum_bytes: int) -> tuple[str, int]: descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) try: before = os.fstat(descriptor) - if ( - not stat.S_ISREG(before.st_mode) - or before.st_size < 0 - or before.st_size > maximum_bytes - ): + if not stat.S_ISREG(before.st_mode) or before.st_size < 0 or before.st_size > maximum_bytes: raise PortableArtifactTransportIntegrityError( "artifact transport member is outside bounds" ) @@ -2126,20 +2135,16 @@ def _hash_regular_file(path: Path, *, maximum_bytes: int) -> tuple[str, int]: byte_length += len(chunk) digest.update(chunk) after = os.fstat(descriptor) - if ( - byte_length != before.st_size - or ( - before.st_dev, - before.st_ino, - before.st_size, - before.st_mtime_ns, - ) - != ( - after.st_dev, - after.st_ino, - after.st_size, - after.st_mtime_ns, - ) + if byte_length != before.st_size or ( + before.st_dev, + before.st_ino, + before.st_size, + before.st_mtime_ns, + ) != ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, ): raise PortableArtifactTransportIntegrityError( "artifact transport member changed while read" diff --git a/src/k1link/observatory/portable_replay.py b/src/k1link/observatory/portable_replay.py index b6425c64..0e78483a 100644 --- a/src/k1link/observatory/portable_replay.py +++ b/src/k1link/observatory/portable_replay.py @@ -26,6 +26,8 @@ from k1link.laboratory.canonical_rerun_overlay import ( canonical_lab_replay, canonical_recording_id, ) +from k1link.laboratory.local_presentations import LOCK as PRESENTATION_LOCK +from k1link.laboratory.local_presentations import LocalPresentations from k1link.observatory.portable_object_replay import ( RENDERER_VERSION as OBJECT_RENDERER_VERSION, ) @@ -68,6 +70,7 @@ class PortableReplayService: media: RecordedMediaInspector, recording_source: Callable[[str], tuple[Path, str] | None], ffmpeg_path: Path, + local_copies: LocalPresentations | None = None, ) -> None: self.view = view self.data_dir = data_dir @@ -75,6 +78,7 @@ class PortableReplayService: self.recording_source = recording_source self.ffmpeg_path = ffmpeg_path self.cache = data_dir / "observatory-portable-replay-cache" + self.local_copies = local_copies self._verified: OrderedDict[tuple[Path, str], tuple[int, ...]] = OrderedDict() def _key(self, result_id: str, base_sha: str) -> tuple[str, dict[str, Any]]: @@ -132,12 +136,15 @@ class PortableReplayService: self._verified[fingerprint] = stamp while len(self._verified) > 32: self._verified.popitem(last=False) - return CanonicalLabReplayArtifact(path, metadata["byte_length"], digest) + artifact = CanonicalLabReplayArtifact(path, metadata["byte_length"], digest) + if self.local_copies is not None: + self.local_copies.register(result_id, artifact, sidecar) + return artifact def prepare(self, result_id: str, base_sha: str) -> CanonicalLabReplayArtifact: # Serialize packaging on the constrained operator host, including # concurrent clicks. Waiting readers cannot start a duplicate render. - with _LOCK: + with PRESENTATION_LOCK, _LOCK: cached = self.cached(result_id, base_sha) if cached is not None: return cached @@ -248,6 +255,8 @@ class PortableReplayService: staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8") os.chmod(staged, 0o600) os.replace(staged, self.cache / f"{key}.json") + if self.local_copies is not None: + self.local_copies.register(result_id, artifact, self.cache / f"{key}.json") return artifact def _composition_key( @@ -305,12 +314,15 @@ class PortableReplayService: self._verified[fingerprint] = stamp while len(self._verified) > 32: self._verified.popitem(last=False) - return CanonicalLabReplayArtifact(path, metadata["byte_length"], digest) + artifact = CanonicalLabReplayArtifact(path, metadata["byte_length"], digest) + if self.local_copies is not None: + self.local_copies.register(run_id, artifact, sidecar) + return artifact def prepare_composition( self, run_id: str, result_ids: tuple[str, ...], base_sha: str ) -> CanonicalLabReplayArtifact: - with _LOCK: + with PRESENTATION_LOCK, _LOCK: cached = self.cached_composition(run_id, result_ids, base_sha) if cached is not None: return cached @@ -445,6 +457,8 @@ class PortableReplayService: staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8") os.chmod(staged, 0o600) os.replace(staged, self.cache / f"{key}.json") + if self.local_copies is not None: + self.local_copies.register(run_id, artifact, self.cache / f"{key}.json") return artifact def _camera(self, session_id: str, bundle: dict[str, Any]) -> RecordedMediaEpoch: diff --git a/src/k1link/observatory/portable_result_cache.py b/src/k1link/observatory/portable_result_cache.py index d8a8766b..de863f0f 100644 --- a/src/k1link/observatory/portable_result_cache.py +++ b/src/k1link/observatory/portable_result_cache.py @@ -124,6 +124,10 @@ class PortableResultCache: or job.active_claimant_id is not None ): return None + if ( + self._sessions.data_dir / "lab-deletions" / "blocked" / (job.result_id + ".json") + ).exists(): + return None try: definition = self._definitions.resolve(job.setup_id, job.definition_sha256) recorded = definition.to_recorded_run_definition() diff --git a/src/k1link/observatory/portable_result_publisher.py b/src/k1link/observatory/portable_result_publisher.py index a8616b80..f4fc623a 100644 --- a/src/k1link/observatory/portable_result_publisher.py +++ b/src/k1link/observatory/portable_result_publisher.py @@ -18,8 +18,8 @@ import json import re import stat from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from pathlib import Path +from dataclasses import dataclass, replace +from pathlib import Path, PurePath, PurePosixPath from typing import cast from k1link.artifact_gateway import ( @@ -73,15 +73,14 @@ from k1link.sessions.models import ( LabReplayCapability, LabSessionBinding, SessionIntegrityError, + SessionNotFoundError, SessionSummary, ) from k1link.sessions.store import SessionStore _COPY_CHUNK_BYTES = 1024 * 1024 _FULL_ROUTE_LABEL = "полный маршрут и воспроизведение" -_LEGACY_CANONICAL_RESULT = re.compile( - r"^lab-v1-vegetation-shadow-[a-f0-9]{64}$" -) +_LEGACY_CANONICAL_RESULT = re.compile(r"^lab-v1-vegetation-shadow-[a-f0-9]{64}$") @dataclass(frozen=True, slots=True) @@ -135,10 +134,9 @@ class PortableObservatoryResultPublisher: "portable result package content address disagrees with queue success" ) source_summary = self._verify_source(job, definition) - artifact_paths = _verify_package_artifacts(root, package.artifacts) - result_document = _read_canonical_result_document( - artifact_paths[RESULT_DOCUMENT_ROLE] - ) + archived_paths = self._retired_artifact_paths(root, package, job) + artifact_paths = _verify_package_artifacts(root, package.artifacts, archived_paths) + result_document = _read_canonical_result_document(artifact_paths[RESULT_DOCUMENT_ROLE]) context = PortableResultValidationContext( manifest=package, job=job, @@ -155,6 +153,12 @@ class PortableObservatoryResultPublisher: "portable result document failed its exact contract validator" ) from exc + existing = self._existing_publication(job, definition, package, profile) + if existing is not None: + binding, artifact_manifest = existing + self._retire_transport(root, package, job, artifact_manifest) + return PublishedPortableObservatoryResult(binding, package, artifact_manifest) + artifact_manifest = self._archive_package( job=job, package=package, @@ -197,22 +201,266 @@ class PortableObservatoryResultPublisher: raise PortableResultPackageIntegrityError( "portable result could not be projected as immutable LAB provenance" ) from exc + # Catalog and immutable archive are durable before transfer duplicates go away. + # The receipt is written first so an interrupted cleanup remains retryable. + self._retire_transport(root, package, job, artifact_manifest) return PublishedPortableObservatoryResult( binding=binding, package=package, artifact_manifest=artifact_manifest, ) + def retire_published_transport( + self, *, job: ObservatoryRecordedJob, package_root: Path + ) -> PublishedPortableObservatoryResult: + """Close an already published transfer, without re-admitting old compute. + + Historical result ownership comes from its immutable catalog and archive. + This method cannot publish a result or add an obsolete definition to the + execution allowlist. Every retained payload is verified before deletion. + """ + _verify_terminal_job(job) + if job.publication_state != "published": + raise PortableResultPublicationBlockedError("result is not durably published") + root, _, package = _read_package(package_root) + try: + binding = self._session_store.get_lab_instance(cast(str, job.result_id)) + if binding is None: + raise ValueError("published result binding is missing") + provenance = binding.provenance + stored_package = provenance["result_package"] + manifest = self._artifact_store.read_manifest(stored_package["artifact_manifest_id"]) + definition_identity = dict(package.run_definition) + definition_sha = definition_identity.pop("definition_sha256") + profile = provenance["calculation_profile"] + result_document = next(a for a in package.artifacts if a.role == RESULT_DOCUMENT_ROLE) + expected_package = { + "schema_version": PORTABLE_RESULT_PACKAGE_SCHEMA, + "manifest_sha256": package.manifest_sha256, + "identity_sha256": package.identity_sha256, + "artifact_manifest_id": manifest.manifest_id, + "result_document_sha256": result_document.sha256, + "artifacts": [a.as_dict() for a in package.artifacts], + } + if ( + root.name != job.result_sha256 + or package.manifest_sha256 != job.result_sha256 + or package.job != job_identity_document(job) + or package.source != source_identity_document(job) + or definition_sha != job.definition_sha256 + or canonical_sha256(definition_identity) != job.definition_sha256 + or package.result["result_id"] != job.result_id + or binding.session_id != job.result_id + or binding.result_id != job.result_id + or binding.source_session_id != job.source_session_id + or binding.source_result_id is not None + or binding.config_sha256 != job.definition_sha256 + or binding.result_kind != package.result["result_kind"] + or provenance["schema_version"] != PORTABLE_RESULT_PUBLICATION_SCHEMA + or provenance["authority"] != OBSERVATION_ONLY_AUTHORITY + or provenance["job"] != package.job + or provenance["source"] != package.source + or provenance["run_definition"] != package.run_definition + or stored_package != expected_package + or profile["definition_sha256"] != job.definition_sha256 + or provenance["calculation_profile_sha256"] != canonical_sha256(profile) + or manifest.metadata.get("calculation-profile-sha256") != canonical_sha256(profile) + or manifest.metadata.get("result-contract-sha256") + != package.result["result_contract_sha256"] + or binding.replay_capability is None + or provenance["replay_capability"] != binding.replay_capability.as_dict() + ): + raise ValueError("published transfer identities differ") + self._archived_artifact_paths(package, job, manifest) + fallback = self._retired_artifact_paths(root, package, job) + _verify_package_artifacts(root, package.artifacts, fallback) + except ( + ArtifactGatewayError, + SessionNotFoundError, + OSError, + KeyError, + TypeError, + ValueError, + ) as exc: + raise PortableResultPackageIntegrityError("published transfer is not verified") from exc + self._retire_transport(root, package, job, manifest) + return PublishedPortableObservatoryResult(binding, package, manifest) + + def _existing_publication( + self, + job: ObservatoryRecordedJob, + definition: PortableRunDefinition, + package: PortableResultPackageManifest, + profile: PortableCalculationProfilePolicy, + ) -> tuple[LabSessionBinding, ArtifactManifest] | None: + # Queue updated_at changes when publication is acknowledged. Neither that + # timestamp nor a later UI label may rewrite immutable published provenance. + try: + summary = self._session_store.get_session(cast(str, job.result_id)).summary + except SessionNotFoundError: + return None + binding = summary.lab + if binding is None: + raise PortableResultPackageIntegrityError("result id belongs to a source recording") + try: + published_profile = binding.provenance["calculation_profile"] + archived_profile = replace(profile, display_name=published_profile["display_name"]) + manifest = self._artifact_store.read_manifest( + binding.provenance["result_package"]["artifact_manifest_id"] + ) + expected_replay = LabReplayCapability( + schema_version="missioncore.observation-lab-replay-capability/v2", + kind="portable-result-review", + viewer_profile="portable-result", + timeline="result-defined", + activation="explicit", + commands_enabled=False, + ) + expected = _publication_provenance( + job=job, + definition=definition, + package=package, + artifact_manifest=manifest, + profile=archived_profile, + replay_capability=expected_replay, + ) + if ( + binding.session_id != job.result_id + or binding.result_id != job.result_id + or binding.source_session_id != job.source_session_id + or binding.source_result_id is not None + or binding.config_sha256 != definition.definition_sha256 + or binding.lab_id != profile.lab_id + or binding.result_kind != definition.result_contract.result_kind + or binding.replay_capability != expected_replay + or binding.provenance != expected + or manifest.metadata.get("calculation-profile-sha256") + != archived_profile.identity_sha256 + or manifest.metadata.get("result-contract-sha256") + != definition.result_contract.contract_sha256 + ): + raise PortableResultPackageIntegrityError("existing publication identity differs") + self._archived_artifact_paths(package, job, manifest) + return binding, manifest + except (ArtifactGatewayError, OSError, KeyError, TypeError, ValueError) as exc: + raise PortableResultPackageIntegrityError("existing publication is invalid") from exc + + def _retired_artifact_paths( + self, + root: Path, + package: PortableResultPackageManifest, + job: ObservatoryRecordedJob, + ) -> dict[str, Path]: + receipt = root / "retired-transport.json" + if not receipt.exists() and not receipt.is_symlink(): + return {} + path = _resolve_local_member(root, PurePosixPath(receipt.name)) + if path.stat().st_size > 4096: + raise PortableResultPackageIntegrityError("transport retirement receipt is too large") + try: + document = json.loads(path.read_bytes()) + manifest_id = document["artifact_manifest_id"] + expected = _retirement_receipt(package, job, manifest_id) + if document != expected or path.read_bytes() != canonical_json(expected): + raise ValueError("retirement identity differs") + manifest = self._artifact_store.read_manifest(manifest_id) + return self._archived_artifact_paths(package, job, manifest) + except (ArtifactGatewayError, OSError, ValueError, KeyError, TypeError) as exc: + raise PortableResultPackageIntegrityError( + "transport archive receipt is invalid" + ) from exc + + def _archived_artifact_paths( + self, + package: PortableResultPackageManifest, + job: ObservatoryRecordedJob, + manifest: ArtifactManifest, + ) -> dict[str, Path]: + expected = { + "package-sha256": package.manifest_sha256, + "package-identity-sha256": package.identity_sha256, + "job-id": job.job_id, + "job-identity-sha256": job.identity_sha256, + "definition-sha256": job.definition_sha256, + "source-bundle-sha256": job.source_bundle_sha256, + } + if ( + manifest.artifact_type != "observatory-portable-result" + or manifest.subject_id != job.result_id + or any(manifest.metadata.get(k) != v for k, v in expected.items()) + ): + raise PortableResultPackageIntegrityError("transport archive identity differs") + paths = {} + members = [(a.role, a.sha256, a.byte_length) for a in package.artifacts] + members.append( + (RESULT_PACKAGE_MANIFEST_ROLE, package.manifest_sha256, len(package.canonical_bytes)) + ) + for role, digest, size in members: + member = manifest.member(role) + if (member.sha256, member.byte_length) != (digest, size): + raise PortableResultPackageIntegrityError("transport archive member differs") + path = self._artifact_store.object_path(digest) + path = _resolve_local_member( + self._artifact_store.root, path.relative_to(self._artifact_store.root) + ) + if _hash_file(path) != (digest, size): + raise PortableResultPackageIntegrityError("transport archive payload differs") + paths[role] = path + return paths + + def _retire_transport( + self, + root: Path, + package: PortableResultPackageManifest, + job: ObservatoryRecordedJob, + manifest: ArtifactManifest, + ) -> None: + # No recursive sweep: only this package's verified, non-shared transfer files. + from .portable_artifact_transport import _write_immutable_file + + try: + self._archived_artifact_paths(package, job, manifest) + _write_immutable_file( + root / "retired-transport.json", + canonical_json(_retirement_receipt(package, job, manifest.manifest_id)), + ) + for artifact in package.artifacts: + path = root / artifact.relative_path + if not path.exists() and not path.is_symlink(): + continue + path = _resolve_package_member(root, artifact.relative_path) + before = path.stat() + if before.st_nlink != 1 or _hash_file(path) != ( + artifact.sha256, + artifact.byte_length, + ): + raise PortableResultPackageIntegrityError( + "changed/shared staging file preserved" + ) + if path.stat() != before: + raise PortableResultPackageIntegrityError("staging changed during retirement") + path.unlink() + # Keep manifest/binding/receipt and directories for exact retries. + import os + + fd = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + except (ArtifactGatewayError, OSError, ValueError) as exc: + raise PortableResultPackageIntegrityError( + "transport retirement incomplete; retry safely" + ) from exc + def _verify_source( self, job: ObservatoryRecordedJob, definition: PortableRunDefinition, ) -> SessionSummary: try: - detail, catalog_sha256 = ( - self._session_store.get_session_with_catalog_snapshot( - job.source_session_id - ) + detail, catalog_sha256 = self._session_store.get_session_with_catalog_snapshot( + job.source_session_id ) except Exception as exc: raise PortableResultPackageIntegrityError( @@ -371,8 +619,7 @@ def resolve_published_portable_calculation_profile( or binding.result_kind != definition.result_contract.result_kind or binding.replay_capability is None or binding.replay_capability.kind != "portable-result-review" - or provenance["replay_capability"] - != binding.replay_capability.as_dict() + or provenance["replay_capability"] != binding.replay_capability.as_dict() ): return None return profile.as_dict() @@ -491,9 +738,7 @@ def _read_package( ) package = PortableResultPackageManifest.from_bytes(payload) if hashlib.sha256(payload).hexdigest() != package.manifest_sha256: - raise PortableResultPackageIntegrityError( - "portable result package manifest digest changed" - ) + raise PortableResultPackageIntegrityError("portable result package manifest digest changed") return root, manifest_path, package @@ -520,9 +765,7 @@ def _verify_package_identity( "portable result package violates its sealed result contract" ) if package.authority != definition.authority.as_dict(): - raise PortableResultPackageIntegrityError( - "portable result package authority changed" - ) + raise PortableResultPackageIntegrityError("portable result package authority changed") def _verify_source_documents( @@ -539,9 +782,7 @@ def _verify_source_documents( "admitted portable source documents are unavailable" ) from exc if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): - raise PortableResultPackageIntegrityError( - "portable source document root is unsafe" - ) + raise PortableResultPackageIntegrityError("portable source document root is unsafe") bundle = _read_content_addressed_document(root, job.source_bundle_sha256) capability = _read_content_addressed_document( root, @@ -638,10 +879,21 @@ def _read_content_addressed_document(root: Path, document_sha256: str) -> dict[s def _verify_package_artifacts( root: Path, artifacts: Sequence[PortableResultArtifact], + archived_paths: Mapping[str, Path] | None = None, ) -> dict[str, Path]: resolved: dict[str, Path] = {} for artifact in artifacts: - path = _resolve_package_member(root, artifact.relative_path) + candidate = root / artifact.relative_path + if not candidate.exists() and not candidate.is_symlink() and archived_paths: + # An archive receipt never excuses an unsafe parent or a corrupt existing file. + current = candidate.parent + while current != root: + if current.is_symlink(): + raise PortableResultPackageIntegrityError("staging parent is a symlink") + current = current.parent + path = archived_paths[artifact.role] + else: + path = _resolve_package_member(root, artifact.relative_path) digest, byte_length = _hash_file(path) if digest != artifact.sha256 or byte_length != artifact.byte_length: raise PortableResultPackageIntegrityError( @@ -652,7 +904,10 @@ def _verify_package_artifacts( def _resolve_package_member(root: Path, relative_path: str) -> Path: - portable = relative_artifact_path(relative_path) + return _resolve_local_member(root, relative_artifact_path(relative_path)) + + +def _resolve_local_member(root: Path, portable: PurePath) -> Path: candidate = root.joinpath(*portable.parts) current = root try: @@ -672,9 +927,7 @@ def _resolve_package_member(root: Path, relative_path: str) -> Path: "portable result artifact is unavailable" ) from exc if not resolved.is_relative_to(root) or not stat.S_ISREG(metadata.st_mode): - raise PortableResultPackageIntegrityError( - "portable result artifact escapes its package" - ) + raise PortableResultPackageIntegrityError("portable result artifact escapes its package") return resolved @@ -688,9 +941,7 @@ def _read_canonical_result_document(path: Path) -> dict[str, object]: ) from exc document = object_document(decoded, "portable result document") if payload != canonical_json(document): - raise PortableResultPackageIntegrityError( - "portable result document is not canonical JSON" - ) + raise PortableResultPackageIntegrityError("portable result document is not canonical JSON") return document @@ -709,10 +960,7 @@ def _publish_exact_member( raise PortableResultPackageIntegrityError( f"portable result artifact could not be archived: {role}" ) from exc - if ( - published.sha256 != expected_sha256 - or published.byte_length != expected_byte_length - ): + if published.sha256 != expected_sha256 or published.byte_length != expected_byte_length: raise PortableResultPackageIntegrityError( f"portable result artifact changed while it was archived: {role}" ) @@ -828,3 +1076,15 @@ def _hash_file(path: Path) -> tuple[str, int]: "portable result artifact could not be read" ) from exc return digest.hexdigest(), byte_length + + +def _retirement_receipt( + package: PortableResultPackageManifest, job: ObservatoryRecordedJob, manifest_id: str +) -> dict[str, object]: + return { + "schema_version": "missioncore.observatory-transport-retirement/v1", + "job_id": job.job_id, + "job_identity_sha256": job.identity_sha256, + "package_sha256": package.manifest_sha256, + "artifact_manifest_id": manifest_id, + } diff --git a/src/k1link/observatory/portable_result_view.py b/src/k1link/observatory/portable_result_view.py index 0dc31267..b7510d17 100644 --- a/src/k1link/observatory/portable_result_view.py +++ b/src/k1link/observatory/portable_result_view.py @@ -30,6 +30,8 @@ class PortableResultViewService: def read(self, result_id: str) -> dict[str, object]: if _RESULT_ID.fullmatch(result_id) is None: raise ValueError("portable result id is invalid") + if (self.sessions.data_dir / "lab-deletions" / "blocked" / (result_id + ".json")).exists(): + raise PortableResultViewError("LAB deletion is in progress or complete") try: binding = self.sessions.get_lab_instance(result_id) except SessionNotFoundError as exc: @@ -50,8 +52,7 @@ class PortableResultViewService: if ( provenance.get("schema_version") != "missioncore.observatory-portable-result-publication/v1" - or provenance.get("replay_capability") - != binding.replay_capability.as_dict() + or provenance.get("replay_capability") != binding.replay_capability.as_dict() or not isinstance(package, dict) or not isinstance(source, dict) or source.get("session_id") != binding.source_session_id @@ -81,8 +82,7 @@ class PortableResultViewService: or manifest.subject_id != result_id or manifest.manifest_id != manifest_id or manifest.metadata.get("package-sha256") != package_sha256 - or package.get("schema_version") - != "missioncore.observatory-portable-result-package/v1" + or package.get("schema_version") != "missioncore.observatory-portable-result-package/v1" or package.get("result_document_sha256") != member.sha256 or member.media_type != "application/json" or not 0 < member.byte_length <= _MAX_RESULT_DOCUMENT_BYTES diff --git a/src/k1link/observatory/recorded_jobs.py b/src/k1link/observatory/recorded_jobs.py index b2a730c3..211dee78 100644 --- a/src/k1link/observatory/recorded_jobs.py +++ b/src/k1link/observatory/recorded_jobs.py @@ -23,7 +23,7 @@ import os import re import sqlite3 import threading -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterator, Sequence from contextlib import contextmanager, suppress from dataclasses import dataclass from datetime import datetime, timedelta @@ -97,6 +97,11 @@ _AUTHORITY: Final = { } _SCHEMA_SQL = """ +CREATE TABLE IF NOT EXISTS observatory_hidden_job_projections ( + job_id TEXT PRIMARY KEY REFERENCES observatory_recorded_jobs(job_id), + hidden_at_utc TEXT NOT NULL +); + CREATE TABLE IF NOT EXISTS simulation_worker_reservation ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), owner_id TEXT NOT NULL, @@ -2203,6 +2208,25 @@ class ObservatoryRecordedJobQueue: with self._read_connection() as connection: return self._get_job(connection, job_id) + def has_source_consumers(self, session_ids: Sequence[str]) -> bool: + """Full durable queue query, including hidden/pending/paused consumers.""" + if not session_ids: + return True + with self._read_connection() as connection: + for session_id in session_ids: + _validate_pattern(session_id, _SESSION_ID, "source session id") + if ( + connection.execute( + "SELECT 1 FROM observatory_recorded_jobs WHERE source_session_id = ? " + "AND (state NOT IN ('succeeded', 'failed') " + "OR publication_state IN ('pending', 'failed')) LIMIT 1", + (session_id,), + ).fetchone() + is not None + ): + return True + return False + def get_by_idempotency_key(self, idempotency_key: str) -> ObservatoryRecordedJob: _validate_pattern(idempotency_key, _IDEMPOTENCY_KEY, "idempotency key") with self._read_connection() as connection: @@ -2216,6 +2240,36 @@ class ObservatoryRecordedJobQueue: ) return _job_from_row(row) + def hide_deleted_projection(self, job_id: str) -> None: + """Finalize a confirmed storage deletion; retain only the bounded job ledger.""" + _validate_pattern(job_id, _JOB_ID, "job id") + with self._transaction() as connection: + job = self._get_job(connection, job_id) + if job.state not in {"failed", "succeeded"}: + raise ObservatoryRecordedQueueConflictError("active work cannot be deleted") + connection.execute( + "INSERT OR IGNORE INTO observatory_hidden_job_projections VALUES (?, ?)", + (job_id, self._clock()), + ) + + def hide_failed_projection(self, job_id: str) -> None: + """Remove a failed attempt from operator history, retaining the audit ledger. + + Successful results and active work cannot be hidden through this action. + Worker scratch retirement is separate and must verify ownership first. + """ + _validate_pattern(job_id, _JOB_ID, "job id") + with self._transaction() as connection: + job = self._get_job(connection, job_id) + if job.state != "failed" or job.result_id is not None: + raise ObservatoryRecordedQueueConflictError( + "only failed attempts without a result can be removed from history" + ) + connection.execute( + "INSERT OR IGNORE INTO observatory_hidden_job_projections VALUES (?, ?)", + (job_id, self._clock()), + ) + def list_jobs( self, *, @@ -2223,6 +2277,7 @@ class ObservatoryRecordedJobQueue: setup_id: str | None = None, definition_sha256: str | None = None, limit: int = 100, + include_hidden: bool = True, ) -> tuple[ObservatoryRecordedJob, ...]: if source_session_id is not None: _validate_pattern(source_session_id, _SESSION_ID, "source session id") @@ -2233,6 +2288,8 @@ class ObservatoryRecordedJobQueue: if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 500: raise ValueError("recorded-job list limit is invalid") clauses: list[str] = [] + if not include_hidden: + clauses.append("job_id NOT IN (SELECT job_id FROM observatory_hidden_job_projections)") parameters: list[object] = [] if source_session_id is not None: clauses.append("source_session_id = ?") diff --git a/src/k1link/observatory/source_transport_lifecycle.py b/src/k1link/observatory/source_transport_lifecycle.py new file mode 100644 index 00000000..06bf202c --- /dev/null +++ b/src/k1link/observatory/source_transport_lifecycle.py @@ -0,0 +1,221 @@ +"""Retire only registered, reproducible source transport copies after use. + +No TTL, model roots, source deletion, or discovery-based blanket cleanup. +Reader locks span HTTP responses. Durable queue references protect pending work. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import stat +import tempfile +from collections.abc import Callable, Iterator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast + +from .recorded_jobs import ObservatoryRecordedQueueError +from .transfer_space import locked_file, secure_directory + + +@dataclass(frozen=True) +class SourceCopy: + path: Path + sha256: str + byte_length: int + + def document(self) -> dict[str, object]: + return {"path": str(self.path.absolute()), "sha256": self.sha256, "bytes": self.byte_length} + + +def _verify(row: dict[str, Any]) -> None: + path = Path(row["path"]) + if not path.is_absolute() or path.resolve() != path: + raise ValueError("Noncanonical source copy") + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + try: + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode) or before.st_size != row["bytes"]: + raise ValueError("Source copy length/type changed") + digest = hashlib.sha256() + while chunk := os.read(fd, 1024 * 1024): + digest.update(chunk) + after = os.fstat(fd) + current = path.stat(follow_symlinks=False) + if ( + (before.st_ino, before.st_size, before.st_mtime_ns) + != ( + after.st_ino, + after.st_size, + after.st_mtime_ns, + ) + or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + != (current.st_dev, current.st_ino, current.st_size, current.st_mtime_ns) + or digest.hexdigest() != row["sha256"] + ): + raise ValueError("Source copy identity changed") + finally: + os.close(fd) + + +def _save(path: Path, row: dict[str, Any]) -> None: + fd, name = tempfile.mkstemp(prefix=".pending-", dir=path.parent) + temporary = Path(name) + try: + if os.fstat(fd).st_nlink != 1: + raise ValueError("Unsafe source ledger") + with os.fdopen(fd, "wb", closefd=False) as stream: + stream.write(json.dumps(row, sort_keys=True).encode()) + stream.flush() + os.fsync(fd) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + os.close(fd) + temporary.unlink(missing_ok=True) + + +class SourceTransportLifecycle: + def __init__(self, root: Path, has_consumers: Callable[[Sequence[str]], bool]) -> None: + self.root = secure_directory(root) + self.ledger = secure_directory(root / ".lifecycle") + self.has_consumers = has_consumers + self._cursor = "" + + def acquire_reader(self) -> int: + import fcntl + + return locked_file(self.ledger / ".readers", fcntl.LOCK_SH) + + @contextmanager + def reading(self) -> Iterator[None]: + fd = self.acquire_reader() + try: + yield + finally: + os.close(fd) + + def register(self, copy: SourceCopy, *, sources: Sequence[SourceCopy], session_id: str) -> None: + """Called under reading(), exclusively for server-admitted producer files.""" + import fcntl + + relative = copy.path.relative_to(self.root) + if relative.parts[0] == ".lifecycle" or not sources: + raise ValueError("Invalid source copy ownership") + key = hashlib.sha256(str(relative).encode()).hexdigest() + path = self.ledger / f"{key}.json" + fd = locked_file(self.ledger / ".metadata", fcntl.LOCK_EX) + try: + previous = self._load(path) if path.exists() else {} + if previous and previous["copy"] != copy.document(): + raise ValueError("Source copy ledger identity conflict") + sessions = sorted(set(previous.get("sessions", [])) | {session_id}) + _save( + path, + { + "version": 1, + "state": "active", + "copy": copy.document(), + "sources": [source.document() for source in sources], + "sessions": sessions, + }, + ) + finally: + os.close(fd) + + def _load(self, path: Path) -> dict[str, Any]: + if path.is_symlink() or not path.is_file() or path.stat().st_size > 16 * 1024 * 1024: + raise ValueError("Unsafe source ledger") + row = json.loads(path.read_bytes()) + if not isinstance(row, dict): + raise ValueError("Invalid source ledger") + target = Path(row["copy"]["path"]) + relative = target.relative_to(self.root) + expected = hashlib.sha256(str(relative).encode()).hexdigest() + ".json" + if row["version"] != 1 or path.name != expected or relative.parts[0] == ".lifecycle": + raise ValueError("Invalid source ledger identity") + if ( + not row["sources"] + or not row["sessions"] + or row["state"] not in {"active", "retiring", "retired"} + ): + raise ValueError("Incomplete source ownership") + return cast(dict[str, Any], row) + + def collect( + self, *, limit: int = 8, only_paths: Sequence[Path] | None = None + ) -> dict[str, int]: + import fcntl + + if not 1 <= limit <= 128: + raise ValueError("Invalid collection bound") + allowed = None if only_paths is None else frozenset(only_paths) + if allowed is not None and any( + not p.is_absolute() or not p.is_relative_to(self.root) or p.resolve() != p + for p in allowed + ): + raise ValueError("Invalid explicit collection scope") + report = {"retired": 0, "bytes": 0, "protected": 0, "unverified": 0, "reading": 0} + try: + fd = locked_file(self.ledger / ".readers", fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + report["reading"] = 1 + return report + try: + if allowed is None: + paths = sorted(self.ledger.glob("*.json")) + else: + paths = sorted( + self.ledger + / (hashlib.sha256(str(p.relative_to(self.root)).encode()).hexdigest() + ".json") + for p in allowed + ) + ordered = [p for p in paths if p.name > self._cursor] + [ + p for p in paths if p.name <= self._cursor + ] + for path in ordered[:limit]: + self._cursor = path.name + try: + row = self._load(path) + if row["state"] == "retired": + continue + if self.has_consumers(row["sessions"]): + report["protected"] += 1 + continue + target = Path(row["copy"]["path"]) + if allowed is not None and target not in allowed: + raise ValueError("Copy is outside explicit collection scope") + # Missing/changed originals preserve the duplicate for recovery. + for source in row["sources"]: + original = Path(source["path"]) + if original.is_relative_to(self.root): + raise ValueError("Another transfer copy is not an original") + _verify(source) + if target.exists() or target.is_symlink(): + _verify(row["copy"]) + if target.stat().st_nlink != 1: + raise ValueError("Shared filesystem owner") + row["state"] = "retiring" + _save(path, row) + target.unlink() + directory = os.open(target.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + report["bytes"] += row["copy"]["bytes"] + row["state"] = "retired" + _save(path, row) + report["retired"] += 1 + except (OSError, ValueError, KeyError, TypeError, ObservatoryRecordedQueueError): + report["unverified"] += 1 + return report + finally: + os.close(fd) diff --git a/src/k1link/observatory/transfer_space.py b/src/k1link/observatory/transfer_space.py new file mode 100644 index 00000000..4e503aca --- /dev/null +++ b/src/k1link/observatory/transfer_space.py @@ -0,0 +1,170 @@ +"""Physical disk admission for transfers, independent of model/LAB complexity. + +One ledger coordinates input and result writers on the same device. Kernel +locks own reservations: process death releases capacity, never payload files. +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import stat +import uuid +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +from k1link.cache_budget import FREE_RESERVE + + +class TransferCapacityError(ValueError): + """A retryable storage shortage, not an invalid model or result.""" + + +def secure_directory(path: Path) -> Path: + path = path.absolute() + if path.resolve() != path: + raise ValueError("Transfer directory is not canonical") + path.mkdir(parents=True, exist_ok=True, mode=0o700) + if not stat.S_ISDIR(path.lstat().st_mode): + raise ValueError("Transfer directory is not a directory") + return path + + +def locked_file(path: Path, operation: int) -> int: + import fcntl + + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + try: + value = os.fstat(fd) + if not stat.S_ISREG(value.st_mode) or value.st_nlink != 1 or value.st_uid != os.getuid(): + raise ValueError("Unsafe transfer lock") + fcntl.flock(fd, operation) + return fd + except BaseException: + os.close(fd) + raise + + +class TransferReservation: + def __init__(self, owner: TransferSpace, fd: int, device: int, remaining: int) -> None: + self.owner, self.fd, self.device, self.remaining = owner, fd, device, remaining + + def _write(self) -> None: + payload = json.dumps( + {"version": 1, "device": self.device, "remaining": self.remaining} + ).encode() + os.lseek(self.fd, 0, os.SEEK_SET) + os.write(self.fd, payload) + os.ftruncate(self.fd, len(payload)) + + def written(self, byte_length: int) -> None: + """Release promised space only after these bytes have reached the file.""" + if byte_length < 0 or byte_length > self.remaining: + raise ValueError("Transfer exceeded its reserved length") + with self.owner.lock(): + self.remaining -= byte_length + self._write() + + +class TransferSpace: + def __init__(self, root: Path, *, reserve_bytes: int = FREE_RESERVE) -> None: + self.root = secure_directory(root) + if reserve_bytes < 0: + raise ValueError("Invalid free-space reserve") + self.reserve_bytes = reserve_bytes + + @contextmanager + def lock(self) -> Iterator[None]: + import fcntl + + fd = locked_file(self.root / ".lock", fcntl.LOCK_EX) + try: + yield + finally: + os.close(fd) + + def _required(self, target: Path, requested: int) -> None: + import fcntl + + if type(requested) is not int or requested < 0: + raise ValueError("Invalid transfer length") + target = secure_directory(target) + device = target.stat().st_dev + promised = 0 + for index, path in enumerate(self.root.glob("reservation-*.json")): + if index >= 10000: + raise TransferCapacityError("Слишком много незавершённых передач.") + if not re.fullmatch(r"reservation-[0-9a-f]{32}\.json", path.name): + raise ValueError("Unknown reservation owner; preserved") + fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW) + try: + st = os.fstat(fd) + if ( + not stat.S_ISREG(st.st_mode) + or st.st_nlink != 1 + or st.st_uid != os.getuid() + or st.st_size > 4096 + ): + raise ValueError("Unsafe transfer reservation") + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + active = True + else: + active = False + if not active: + # Canonical UUID metadata in this private ledger has no live + # owner. It may be torn by a crash; never follow paths from it. + # Any partial payload remains counted by filesystem free space. + path.unlink() + continue + row = json.loads(os.read(fd, 4096)) + if ( + set(row) != {"version", "device", "remaining"} + or row["version"] != 1 + or type(row["remaining"]) is not int + or row["remaining"] < 0 + or type(row["device"]) is not int + ): + raise ValueError("Unknown live reservation schema; preserved") + if row["device"] == device: + promised += row["remaining"] + finally: + os.close(fd) + available = max(0, shutil.disk_usage(target).free - promised - self.reserve_bytes) + if requested > available: + raise TransferCapacityError( + f"Недостаточно места для передачи: нужно {requested} байт, " + f"доступно {available} байт с учётом текущих передач и резерва." + ) + + def check(self, target: Path, requested: int) -> None: + """Advisory package preflight; each actual write reserves again atomically.""" + with self.lock(): + self._required(target, requested) + + @contextmanager + def reservation(self, target: Path, requested: int) -> Iterator[TransferReservation]: + import fcntl + + path = self.root / f"reservation-{uuid.uuid4().hex}.json" + with self.lock(): + self._required(target, requested) + fd = locked_file(path, fcntl.LOCK_EX) + reservation = TransferReservation(self, fd, target.stat().st_dev, requested) + try: + reservation._write() + os.fsync(fd) + except BaseException: + os.close(fd) + path.unlink(missing_ok=True) + raise + try: + yield reservation + finally: + with self.lock(): + path.unlink(missing_ok=True) + os.close(fd) diff --git a/src/k1link/sessions/camera_frame.py b/src/k1link/sessions/camera_frame.py index 353eb75c..b6c38ae9 100644 --- a/src/k1link/sessions/camera_frame.py +++ b/src/k1link/sessions/camera_frame.py @@ -6,6 +6,7 @@ import struct import subprocess import threading from collections import OrderedDict +from collections.abc import Callable from contextlib import suppress from dataclasses import dataclass from pathlib import Path @@ -70,18 +71,20 @@ class RecordedCameraFrameService: def __init__( self, - store: SessionStore, + store: SessionStore | None, inspector: RecordedMediaInspector, *, ffmpeg_path: Path, cache_root: Path, max_decode_lanes: int = _DEFAULT_MAX_DECODE_LANES, max_source_manifests: int = _DEFAULT_MAX_SOURCE_MANIFESTS, + manifest_provider: Callable[[str, str], RecordedMediaManifest] | None = None, ) -> None: resolved_ffmpeg = ffmpeg_path.expanduser().resolve(strict=True) if not resolved_ffmpeg.is_file() or not os.access(resolved_ffmpeg, os.X_OK): raise SessionIntegrityError("ffmpeg is unavailable for camera frame review") self._store = store + self._manifest_provider = manifest_provider self._inspector = inspector self._ffmpeg_path = resolved_ffmpeg self._cache_root = cache_root.expanduser().absolute() @@ -217,16 +220,21 @@ class RecordedCameraFrameService: self._source_manifests.move_to_end(source_key) if cached is not None: return cached - replay = self._store.prepare_replay(session_id, speed=1.0, loop=False) - matches = tuple( - artifact - for artifact in self._store.list_recorded_media(session_id) - if artifact.source_path.name == expected_source_name - ) - if len(matches) != 1: - raise SessionIntegrityError("recorded camera source is unavailable") - artifact = matches[0] - manifest = self._inspector.inspect(artifact, replay) + if self._manifest_provider is not None: + manifest = self._manifest_provider(session_id, expected_source_name) + else: + if self._store is None: + raise SessionIntegrityError("Recorded camera source provider is unavailable") + replay = self._store.prepare_replay(session_id, speed=1.0, loop=False) + matches = tuple( + artifact + for artifact in self._store.list_recorded_media(session_id) + if artifact.source_path.name == expected_source_name + ) + if len(matches) != 1: + raise SessionIntegrityError("recorded camera source is unavailable") + artifact = matches[0] + manifest = self._inspector.inspect(artifact, replay) with self._coordination: bound = self._source_manifests.get(source_key) if bound is None: diff --git a/src/k1link/sessions/store.py b/src/k1link/sessions/store.py index f4e34a50..225fd043 100644 --- a/src/k1link/sessions/store.py +++ b/src/k1link/sessions/store.py @@ -502,6 +502,8 @@ class SessionStore: raise ValueError("LAB id must use the form 'LAB E21'") _validate_identifier(result_kind, "LAB result kind") _validate_identifier(result_id, "LAB result id") + if (self.data_dir / "lab-deletions" / "blocked" / (result_id + ".json")).exists(): + raise SessionIntegrityError("LAB was explicitly deleted; republication is blocked") if source_result_id is not None: _validate_identifier(source_result_id, "LAB source result id") if config_sha256 is not None and SHA256_PATTERN.fullmatch(config_sha256) is None: @@ -763,6 +765,12 @@ class SessionStore: connection.commit() return normalized_name + def validate_lab_projection(self, session_id: str) -> None: + """Validate catalog ownership before any physical storage mutation.""" + _validate_identifier(session_id, "LAB session id") + with self._lock, self._connect() as connection: + _require_capability_owned_lab_projection(connection, session_id) + def delete_capability_lab_projection(self, session_id: str) -> None: """Delete only one typed LAB catalog projection and its copied rows. @@ -1868,10 +1876,10 @@ def _require_capability_owned_lab_projection( if ( summary["archive_id"] != LAB_ARCHIVE_ID or summary["origin"] != LAB_ORIGIN - or binding.replay_capability is None or binding.session_id != session_id or binding.source_session_id == session_id - or lab["include_recorded_media"] not in {0, 1} + or (lab["include_recorded_media"] not in {0, 1} + and binding.replay_capability is not None) or connection.execute( "SELECT 1 FROM observation_lab_instances WHERE session_id = ?", (binding.source_session_id,), @@ -1882,6 +1890,16 @@ def _require_capability_owned_lab_projection( "observation session is not a capability-owned LAB projection" ) _operator_display_name_from_row(lab["operator_display_name"]) + if binding.replay_capability is None: + # Old publications predate the media-copy flag. Catalog mutations do not + # grant replay and never traverse or remove evidence paths. + source = connection.execute( + "SELECT origin FROM observation_sessions WHERE session_id = ?", + (binding.source_session_id,), + ).fetchone() + if source is None or source["origin"] == LAB_ORIGIN: + raise SessionIntegrityError("LAB projection source ownership is invalid") + return summary, lab _validate_existing_lab_projection( connection, session_id=session_id, @@ -1891,7 +1909,8 @@ def _require_capability_owned_lab_projection( duration_seconds=summary["duration_seconds"], include_recorded_media=bool(lab["include_recorded_media"]), require_recorded_replay=( - binding.replay_capability.viewer_profile == "recorded-session" + binding.replay_capability is not None + and binding.replay_capability.viewer_profile == "recorded-session" ), ) return summary, lab diff --git a/src/k1link/web/app.py b/src/k1link/web/app.py index f534f378..1fee6474 100644 --- a/src/k1link/web/app.py +++ b/src/k1link/web/app.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import logging import os import shutil from collections.abc import AsyncIterator, Iterable @@ -15,26 +16,17 @@ from pydantic import ValidationError from k1link import __version__ from k1link.artifact_gateway import configured_artifact_gateway -from k1link.compute import ( - IntegratedPerceptionOverlayStore, - RecordedCalibratedFusionStore, - RecordedPerceptionEpochStore, - RecordedPerceptionOverlayMux, - RecordedPerceptionOverlayStore, -) -from k1link.compute.pipeline_telemetry import JsonlPipelineTelemetrySink -from k1link.laboratory import ( - LaboratoryEvidenceRegistry, - LaboratoryEvidenceReportService, - LaboratoryExecutionRegistry, - LaboratoryRunner, - LaboratoryValueReviewRegistry, -) -from k1link.laboratory.m48_raw_evidence import ( - M48_EXPECTED_THREAT_RESULT_ID, - M48RawEvidenceError, - M48RawEvidenceReader, +from k1link.laboratory.deletion_coordinator import LabDeletionCoordinator +from k1link.laboratory.local_presentations import LocalPresentations +from k1link.laboratory.worker_gateway import ( + LaboratoryGatewayConfiguration, + LaboratoryWorkerGateway, + build_laboratory_worker_gateway_router, ) +from k1link.missions.default_sources import DefaultPlanningSources +from k1link.missions.drafts import MissionDrafts +from k1link.missions.registration_runs import RegistrationRuns +from k1link.missions.sources import PlanningSources from k1link.observatory import ( LaboratorySetupRegistry, LaboratorySetupRegistryError, @@ -94,6 +86,7 @@ from k1link.observatory.recorded_jobs import ( ObservatoryRecordedQueueError, RecordedRunDefinitionRegistry, ) +from k1link.reconstruction.session_versions import SessionMapVersions from k1link.sessions import ( MaterializedRecording, RecordedCameraFrameService, @@ -106,111 +99,29 @@ from k1link.sessions import ( SessionRecordingPreparationManager, SessionStore, ) +from k1link.sessions.map_recording import MapReplaySessionStore from k1link.sessions.models import SessionSummary +from k1link.sessions.overview import SessionOverviewService from k1link.simulation.projects import SimulationProjectService, SimulationProjectStore -from k1link.web.advanced_laboratory_api import build_advanced_laboratory_router +from k1link.web.ai_polygon_api import build_ai_polygon_router from k1link.web.artifact_health_api import build_artifact_health_router from k1link.web.compute_contour_api import build_compute_contour_router -from k1link.web.fleet_api import router as fleet_router -from k1link.web.independent_equipment_api import router as equipment_router -from k1link.web.equipment_firmware_api import router as equipment_firmware_router -from k1link.web.installer_api import router as installer_router -from k1link.web.vps_host_api import router as vps_host_router, start as start_vps_hosts -from k1link.web.rover_api import router as rover_router from k1link.web.device_plugin_composition import load_installed_device_plugins -from k1link.web.e30_engineering_api import build_e30_engineering_router -from k1link.web.e30_human_review_api import build_e30_human_review_router -from k1link.web.e30_review_api import build_e30_review_router -from k1link.web.e40_case_review_api import build_e40_case_review_router -from k1link.web.e46_blind_review_api import build_e46_blind_review_router -from k1link.web.e46a_ai_engineering_preannotation_api import ( - build_e46a_ai_engineering_preannotation_router, -) -from k1link.web.e46b_temporal_motion_api import build_e46b_temporal_motion_router -from k1link.web.e46c_full_replay_world_tracks_api import ( - build_e46c_full_replay_world_tracks_router, -) -from k1link.web.e46d_temporal_failure_audit_api import ( - build_e46d_temporal_failure_audit_router, -) -from k1link.web.e46e_ready_stack_api import build_e46e_ready_stack_router -from k1link.web.e46f_dashcam_bakeoff_api import build_e46f_dashcam_bakeoff_router -from k1link.web.e46g_rectified_detector_bakeoff_api import ( - build_e46g_rectified_detector_bakeoff_router, -) -from k1link.web.e46h_full_rectified_front_replay_api import ( - build_e46h_full_rectified_front_replay_router, -) -from k1link.web.e46i_grounding_dino_full_replay_api import ( - build_e46i_grounding_dino_full_replay_router, -) -from k1link.web.e46j_raw_fisheye_realtime_api import ( - build_e46j_raw_fisheye_realtime_router, -) -from k1link.web.e47_semantic_slam_api import build_e47_semantic_slam_router from k1link.web.environment_api import build_environment_router +from k1link.web.equipment_firmware_api import router as equipment_firmware_router +from k1link.web.fleet_api import router as fleet_router from k1link.web.frontend_assets import ControlStationStaticFiles, frontend_build_id -from k1link.web.response_compression import ResponseCompressionMiddleware -from k1link.web.runtime_http_timing import RuntimeHttpTimingMiddleware -from k1link.web.l3_pointpillars_visual_api import ( - build_l3_pointpillars_visual_router, -) -from k1link.web.l31_pointpillars_ravnoves_api import ( - build_l31_pointpillars_ravnoves_router, -) -from k1link.web.l32_pointpillars_camera_review_api import ( - build_l32_pointpillars_camera_review_router, -) -from k1link.web.l33_camera_first_detector_review_api import ( - build_l33_camera_first_detector_review_router, -) -from k1link.web.l34_annotation_api import ( - build_l34_annotation_router, - build_l34d_blind_annotation_router, -) -from k1link.web.l34_right_yolox_truth_island_api import ( - build_l34_right_yolox_truth_island_freeze_router, -) -from k1link.web.l34a_assisted_yolox_error_audit_api import ( - build_l34a_assisted_yolox_error_audit_router, -) -from k1link.web.l34b_nested_box_consolidation_api import ( - build_l34b_nested_box_consolidation_router, -) -from k1link.web.l34c_tile_seam_stitch_api import ( - build_l34c_tile_seam_stitch_router, -) -from k1link.web.l34d_cumulative_postprocessing_api import ( - build_l34d_cumulative_postprocessing_router, -) -from k1link.web.l34e_self_review_diagnostic_api import ( - build_l34e_self_review_diagnostic_router, -) -from k1link.web.l34f_adjudication_api import build_l34f_adjudication_router -from k1link.web.laboratory_api import build_laboratory_router -from k1link.web.laboratory_report_api import build_laboratory_report_router -from k1link.web.lidar_api import build_lidar_router -from k1link.web.lidar_local_surface_service import K1LocalSurfaceReadService -from k1link.web.m4_threat_replay_api import build_m4_threat_replay_router -from k1link.web.m48_object_quality_api import build_m48_object_quality_router -from k1link.web.m48r3_static_occupancy_api import ( - build_m48r3_static_occupancy_router, -) -from k1link.web.m48s_fixed_class_detector_lab_api import ( - build_m48s_fixed_class_detector_lab_router, -) -from k1link.web.m48t_risk_quality_lab_api import build_m48t_risk_quality_lab_router -from k1link.web.m49_physical_safety_playback_api import ( - build_m49_physical_safety_playback_router, -) -from k1link.web.m49_tgs_fail_closed_api import build_m49_tgs_fail_closed_router -from k1link.web.m49_tgs_full_shadow_api import build_m49_tgs_full_shadow_router +from k1link.web.independent_equipment_api import router as equipment_router +from k1link.web.installer_api import router as installer_router +from k1link.web.local_storage_api import build_local_storage_router from k1link.web.map_api import ( MapGatewayConfiguration, MapGatewayProxy, build_map_router, ) from k1link.web.map_view_api import build_map_view_router +from k1link.web.mission_planner_api import build_mission_planner_router +from k1link.web.mission_registration_api import build_mission_registration_router from k1link.web.modular_observatory_api import build_modular_observatory_router from k1link.web.observatory_api import build_observatory_router from k1link.web.observatory_worker_api import ( @@ -230,7 +141,10 @@ from k1link.web.plugin_runtime import ( ) from k1link.web.polygon_api import build_polygon_router, configured_polygon_runs_root from k1link.web.portable_replay_api import build_portable_replay_router +from k1link.web.response_compression import ResponseCompressionMiddleware +from k1link.web.rover_api import router as rover_router from k1link.web.runtime_diagnostics import configure_scanner_diagnostics +from k1link.web.runtime_http_timing import RuntimeHttpTimingMiddleware from k1link.web.runtime_readiness import ( BackgroundReconcilerReadiness, build_runtime_readiness, @@ -238,41 +152,15 @@ from k1link.web.runtime_readiness import ( from k1link.web.scene_profiles_api import build_scene_profiles_router from k1link.web.session_api import build_session_router from k1link.web.session_overview_api import build_session_overview_router -from k1link.sessions.overview import SessionOverviewService -from k1link.missions.sources import PlanningSources -from k1link.missions.drafts import MissionDrafts -from k1link.missions.registration_runs import RegistrationRuns -from k1link.web.mission_registration_api import build_mission_registration_router -from k1link.web.mission_planner_api import build_mission_planner_router from k1link.web.simulation_projects_api import build_simulation_projects_router -from k1link.web.ai_polygon_api import build_ai_polygon_router from k1link.web.simulation_world_provider_api import build_simulation_world_provider_router from k1link.web.system_telemetry_api import build_system_telemetry_router -from k1link.web.vegetation_shadow_lab_api import ( - build_vegetation_benchmark_lab_router, - build_vegetation_shadow_lab_router, -) from k1link.web.viewer_diagnostics_api import build_viewer_diagnostics_router +from k1link.web.vps_host_api import router as vps_host_router +from k1link.web.vps_host_api import start as start_vps_hosts REPOSITORY_ROOT = Path(__file__).resolve().parents[3] INVALID_REQUEST_DETAIL = "Некорректные параметры запроса." -LABORATORY_EVIDENCE_REGISTRY = LaboratoryEvidenceRegistry.from_directory( - REPOSITORY_ROOT / "config" / "laboratories" -) -LABORATORY_EXECUTION_REGISTRY = LaboratoryExecutionRegistry.from_file( - REPOSITORY_ROOT / "config" / "laboratory-execution.json", - LABORATORY_EVIDENCE_REGISTRY, -) -LABORATORY_RUNNER = LaboratoryRunner( - registry=LABORATORY_EXECUTION_REGISTRY, - evidence_registry=LABORATORY_EVIDENCE_REGISTRY, - sink=JsonlPipelineTelemetrySink( - REPOSITORY_ROOT / ".runtime" / "telemetry" / "laboratory-runs.jsonl" - ), -) -LABORATORY_VALUE_REVIEW_REGISTRY = LaboratoryValueReviewRegistry.from_file( - REPOSITORY_ROOT / "config" / "laboratory-value-review.json" -) OBSERVATORY_LABORATORY_SETUP_REGISTRY: LaboratorySetupRegistry | None OBSERVATORY_LABORATORY_SETUP_REGISTRY_ERROR: str | None try: @@ -287,10 +175,6 @@ except (LaboratorySetupRegistryError, OSError) as exc: # starting. OBSERVATORY_LABORATORY_SETUP_REGISTRY = None OBSERVATORY_LABORATORY_SETUP_REGISTRY_ERROR = str(exc) -LABORATORY_EVIDENCE_REPORTS = LaboratoryEvidenceReportService( - LABORATORY_EVIDENCE_REGISTRY, - lambda: REPOSITORY_ROOT / ".runtime" / "compute-experiments", -) def _resolve_media_tool(name: str) -> Path | None: @@ -470,17 +354,12 @@ OBSERVATORY_WORKER_API_ERROR: str | None simulation_project_store = SimulationProjectStore(session_store.data_dir) simulation_project_service = SimulationProjectService(simulation_project_store) session_artifact_gateway = configured_artifact_gateway(session_store.data_dir) -lidar_local_surface_read_service = K1LocalSurfaceReadService( - session_store.data_dir / "lidar-read-cache" -) + session_recording_materializer = SessionRecordingMaterializer( session_store.data_dir, exporters=plugin_environment.recording_exporters, artifact_gateway=session_artifact_gateway, ) -from k1link.reconstruction.session_versions import SessionMapVersions -from k1link.sessions.map_recording import MapReplaySessionStore -from k1link.missions.default_sources import DefaultPlanningSources session_map_versions = SessionMapVersions(session_store.data_dir) operator_session_store = MapReplaySessionStore(session_store, session_map_versions) @@ -494,6 +373,7 @@ mission_drafts = MissionDrafts(session_store.data_dir / 'missions', mission_registration_runs = RegistrationRuns(mission_drafts) from k1link.missions.live_tests import PlanningLiveTests from k1link.web.planning_live_api import build_planning_live_router + planning_live_tests = PlanningLiveTests(mission_drafts, plugin_environment.live_planning_sources, mission_registration_runs.lock, capture_recorder=session_store.record_planning_capture) @@ -652,72 +532,11 @@ session_recorded_camera_frame_service = ( else None ) try: - m48_raw_evidence_reader: M48RawEvidenceReader | None = M48RawEvidenceReader.from_repository( - repository_root=REPOSITORY_ROOT, - threat_result_root=( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m4" - / "replay-threat" - / M48_EXPECTED_THREAT_RESULT_ID - ), - ) -except (M48RawEvidenceError, OSError, ValueError): - m48_raw_evidence_reader = None -session_legacy_perception_overlay_store = ( - RecordedPerceptionOverlayStore( - jobs_root=REPOSITORY_ROOT / ".runtime" / "compute-jobs", - results_root=REPOSITORY_ROOT / ".runtime" / "compute-results", - cache_root=session_store.data_dir / "perception-overlays", - ffmpeg_path=_ffmpeg, - ffprobe_path=_ffprobe, - ) - if _ffmpeg is not None and _ffprobe is not None - else None -) -session_calibrated_fusion_store = RecordedCalibratedFusionStore( - jobs_root=REPOSITORY_ROOT / ".runtime" / "compute-jobs", - perception_results_root=REPOSITORY_ROOT / ".runtime" / "compute-results", - fusion_results_root=REPOSITORY_ROOT / ".runtime" / "compute-fusions", - cache_root=session_store.data_dir / "calibrated-fusion-overlays", -) -session_previous_perception_overlay_store = RecordedPerceptionOverlayMux( - session_calibrated_fusion_store, session_legacy_perception_overlay_store -) -session_integrated_perception_store = ( - IntegratedPerceptionOverlayStore( - jobs_root=REPOSITORY_ROOT / ".runtime" / "compute-jobs", - results_root=( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e10" / "worker-results" - ), - lidar_packs_root=( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e10" / "lidar-packs" - ), - cache_root=session_store.data_dir / "integrated-perception-overlays", - ffmpeg_path=_ffmpeg, - artifact_gateway=session_artifact_gateway, - ) - if _ffmpeg is not None - else None -) -session_perception_overlay_store = RecordedPerceptionOverlayMux( - session_integrated_perception_store or session_previous_perception_overlay_store, - ( - session_previous_perception_overlay_store - if session_integrated_perception_store is not None - else None - ), -) -session_perception_epoch_store = ( - RecordedPerceptionEpochStore( - jobs_root=REPOSITORY_ROOT / ".runtime" / "compute-jobs", - results_root=REPOSITORY_ROOT / ".runtime" / "compute-results", - ffprobe_path=_ffprobe, - ) - if _ffprobe is not None - else None -) + lab_gateway_configuration = LaboratoryGatewayConfiguration.from_file( + session_store.data_dir / "laboratory-worker-gateway.json") +except (OSError, ValueError): + lab_gateway_configuration = None +laboratory_worker_gateway = LaboratoryWorkerGateway(lab_gateway_configuration) map_gateway_proxy = MapGatewayProxy(MapGatewayConfiguration.from_environment()) recording_reconciler_readiness = BackgroundReconcilerReadiness() @@ -770,14 +589,15 @@ def _m48_recorded_camera_playback_source( return session_recorded_camera_frame_service.playback_source(session_id) -def _canonical_lab_recording_source(session_id: str) -> tuple[Path, str] | None: - """Resolve one already-published immutable RRD without starting new work.""" + +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 or snapshot.state != "ready" or snapshot.recording is None: return None if snapshot.command.map_version is not None: - return None # Original-frame LAB overlays cannot consume corrected operator geometry. + return None return snapshot.recording.path, snapshot.recording.sha256 @@ -922,6 +742,8 @@ async def _portable_result_publication_reconciler() -> None: # bounded pass or through the explicit operator action. with suppress(OSError, ValueError): await asyncio.to_thread(service.run_once) + with suppress(OSError, ValueError): + await asyncio.to_thread(service.artifact_transport.collect_source_copies) await asyncio.sleep(15.0) @@ -933,6 +755,17 @@ async def _recorded_blueprint_resource_reaper() -> None: await asyncio.to_thread(recorded_blueprint_sessions.expire) +async def _local_copy_reaper() -> None: + while True: + try: + await asyncio.to_thread(local_presentation_copies.prune) + except (OSError, ValueError): + logging.getLogger(__name__).exception( + "Local presentation retention failed; files preserved" + ) + await asyncio.sleep(3600) + + @asynccontextmanager async def app_lifespan(application: FastAPI) -> AsyncIterator[None]: import logging @@ -956,6 +789,7 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]: reconciler: asyncio.Task[None] | None = None publication_reconciler: asyncio.Task[None] | None = None blueprint_reaper: asyncio.Task[None] | None = None + local_copy_reaper: asyncio.Task[None] | None = None try: configure_scanner_diagnostics(session_store.data_dir / "logs") session_recording_preparation_manager.start() @@ -971,6 +805,7 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]: reconciler = asyncio.create_task(_recording_preparation_reconciler()) publication_reconciler = asyncio.create_task(_portable_result_publication_reconciler()) blueprint_reaper = asyncio.create_task(_recorded_blueprint_resource_reaper()) + local_copy_reaper = asyncio.create_task(_local_copy_reaper()) yield finally: from k1link.viewer.recorded import recorded_blueprint_sessions @@ -978,6 +813,10 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]: application.state.fleet = None if fleet is not None: await asyncio.to_thread(fleet.close) + if local_copy_reaper is not None: + local_copy_reaper.cancel() + with suppress(asyncio.CancelledError): + await local_copy_reaper if blueprint_reaper is not None: blueprint_reaper.cancel() with suppress(asyncio.CancelledError): @@ -996,7 +835,6 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]: await asyncio.to_thread(session_overview_service.close) await asyncio.to_thread(planning_live_tests.close) await asyncio.to_thread(mission_registration_runs.close) - await asyncio.to_thread(lidar_local_surface_read_service.close) plugin_environment.close() @@ -1155,6 +993,14 @@ async def device_plugin_events(websocket: WebSocket, plugin_id: str) -> None: await websocket.close(code=1011, reason="Device plugin state stream failed") +local_presentation_copies = LocalPresentations(session_store.data_dir) +lab_deletion_service = LabDeletionCoordinator( + store=session_store, queue=OBSERVATORY_RECORDED_JOB_QUEUE, + compositions=OBSERVATORY_AI_COMPOSITION_RUNS, copies=local_presentation_copies, + gateway=laboratory_worker_gateway.configuration, +) +app.include_router(build_local_storage_router(local_presentation_copies)) + if session_artifact_gateway is not None and _ffmpeg is not None: app.include_router( build_portable_replay_router( @@ -1166,6 +1012,7 @@ if session_artifact_gateway is not None and _ffmpeg is not None: media=session_recorded_media_inspector, recording_source=_canonical_lab_recording_source, ffmpeg_path=_ffmpeg, + local_copies=local_presentation_copies, ), composition_runs=OBSERVATORY_AI_COMPOSITION_RUNS, queue=OBSERVATORY_RECORDED_JOB_QUEUE, @@ -1189,8 +1036,7 @@ app.include_router( recording_materializer=session_recording_materializer, recording_preparation_manager=session_recording_preparation_manager, media_inspector=session_recorded_media_inspector, - perception_overlay_provider=session_perception_overlay_store, - perception_media_provider=session_perception_epoch_store, + laboratory_gateway=laboratory_worker_gateway, point_color_renderers=plugin_environment.point_color_renderers, point_display_renderers=plugin_environment.point_display_renderers, lab_calculation_profile_resolver=( @@ -1206,6 +1052,7 @@ app.include_router( app.include_router( build_observatory_router( session_store, + deletion_service=lab_deletion_service, setup_registry=OBSERVATORY_LABORATORY_SETUP_REGISTRY, setup_registry_error=OBSERVATORY_LABORATORY_SETUP_REGISTRY_ERROR, run_preparation_ledger=OBSERVATORY_RUN_PREPARATION_LEDGER, @@ -1251,6 +1098,7 @@ if ( binding=OBSERVATORY_PORTABLE_BINDING_SERVICE, queue=OBSERVATORY_RECORDED_JOB_QUEUE, view_profiles=OBSERVATORY_LAB_VIEW_PROFILES, + deletion_service=lab_deletion_service, ) ) if OBSERVATORY_WORKER_DISPATCH_READY: @@ -1268,6 +1116,7 @@ if OBSERVATORY_WORKER_DISPATCH_READY: app.include_router( build_environment_router(root_provider=lambda: session_store.data_dir / "ui-environment") ) +app.include_router(build_scene_profiles_router(lambda: session_store.data_dir / "scene-profiles")) app.include_router(build_map_router(map_gateway_proxy)) app.include_router( build_map_view_router( @@ -1281,707 +1130,9 @@ app.include_router( ) ) ) +app.include_router(build_laboratory_worker_gateway_router(laboratory_worker_gateway)) app.include_router( - build_lidar_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "lidar-replay-v2" / "packs" - ), - ground_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "lidar-ground-v1" / "benchmarks" - ), - field_review_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "lidar-field-review-v1" - / "reviews" - ), - local_surface_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "k1-local-surface-v1" / "models" - ), - e10_source_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e10" / "lidar-packs" - ), - dataset_admission_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "dataset-gateway" / "admission.json" - ), - dataset_preview_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "dataset-gateway" / "preview.json" - ), - dataset_rellis_preview_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "dataset-gateway" / "rellis-preview.json" - ), - dataset_rellis_admission_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "dataset-gateway" / "rellis-admission.json" - ), - dataset_ground_preview_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "dataset-gateway" / "ground-comparison.json" - ), - local_surface_read_service=lidar_local_surface_read_service, - ) -) -app.include_router( - build_laboratory_router( - e29_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e29" / "results" - ), - local_surface_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "k1-local-surface-v1" / "models" - ), - source_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e10" / "lidar-packs" - ), - source_result_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e10" / "worker-results" - ), - ) -) -app.include_router( - build_laboratory_report_router( - LABORATORY_VALUE_REVIEW_REGISTRY, - LABORATORY_EVIDENCE_REPORTS, - ) -) -app.include_router( - build_advanced_laboratory_router( - evidence_registry=LABORATORY_EVIDENCE_REGISTRY, - evidence_runtime_root_provider=lambda: REPOSITORY_ROOT / ".runtime" / "compute-experiments", - e31_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e31" / "source-qualifications" - ), - e32_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e32" / "results" - ), - e33_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e33" / "results" - ), - e34_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e34" / "results" - ), - e35_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e35" / "results" - ), - e37_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e37" / "results" - ), - e38_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e38" / "results" - ), - e39_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e39" / "results" - ), - e40_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e40" / "results" - ), - l3_visual_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "visual-audits" - ), - l31_ravnoves_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "pointpillars-ravnoves" - ), - l32_camera_review_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "pointpillars-camera-review" - ), - l33_camera_first_review_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "camera-first-detector-review" - ), - ) -) -app.include_router( - build_l3_pointpillars_visual_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "visual-audits" - ) - ) -) -app.include_router( - build_l31_pointpillars_ravnoves_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "pointpillars-ravnoves" - ) - ) -) -app.include_router( - build_l32_pointpillars_camera_review_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "pointpillars-camera-review" - ) - ) -) -app.include_router( - build_l33_camera_first_detector_review_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "camera-first-detector-review" - ) - ) -) -app.include_router( - build_l34_right_yolox_truth_island_freeze_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - ) -) -app.include_router( - build_e46_blind_review_router( - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - annotation_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "laboratory-annotations" / "e46-blind" - ), - submission_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e48" / "review-submissions" - ), - ) -) -app.include_router( - build_e46a_ai_engineering_preannotation_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "e46a" - / "ai-engineering-preannotations" - ), - annotation_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "laboratory-annotations" / "e46a-correction" - ), - ) -) -app.include_router( - build_e46b_temporal_motion_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46b" / "temporal-motion" - ), - ) -) -app.include_router( - build_e46c_full_replay_world_tracks_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "e46c" - / "full-replay-world-tracks" - ), - e26_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e10" / "worker-results" - ), - ) -) -app.include_router( - build_e46d_temporal_failure_audit_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "e46d" - / "temporal-failure-audits" - ), - ) -) -app.include_router( - build_m4_threat_replay_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "m4" / "replay-threat" - ), - repository_root_provider=lambda: REPOSITORY_ROOT, - camera_frame_provider=( - session_recorded_camera_frame_service.extract - if session_recorded_camera_frame_service is not None - else None - ), - ) -) -app.include_router( - build_m48_object_quality_router( - pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "m48" / "object-quality-packs" - ), - workflow_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "laboratory-annotations" / "m48-object-quality" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "m48" / "object-truth-seals" - ), - result_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "m48" / "object-quality-results" - ), - small_static_result_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m48" - / "small-static-passage-regression-results" - ), - static_occupancy_result_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m48" - / "static-occupancy-qualification-results" - ), - camera_frame_provider=( - session_recorded_camera_frame_service.extract - if session_recorded_camera_frame_service is not None - else None - ), - camera_playback_provider=( - _m48_recorded_camera_playback_source - if session_recorded_camera_frame_service is not None - else None - ), - spatial_evidence_provider=m48_raw_evidence_reader, - evaluation_runner=LABORATORY_RUNNER, - evaluation_receipt_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "laboratory-run-receipts" - ), - ) -) -app.include_router( - build_m48r3_static_occupancy_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m48" - / "static-occupancy-shadow-results" - ), - repository_root_provider=lambda: REPOSITORY_ROOT, - camera_frame_provider=( - session_recorded_camera_frame_service.extract - if session_recorded_camera_frame_service is not None - else None - ), - ) -) -app.include_router( - build_m49_tgs_fail_closed_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "m49" / "tgs-fail-closed-results" - ), - ) -) -app.include_router( - build_m49_tgs_full_shadow_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "m49" / "tgs-full-shadow-results" - ), - ) -) -app.include_router( - build_vegetation_shadow_lab_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "lab-v1-vegetation" / "results" - ), - canonical_recording_provider=_canonical_lab_recording_source, - camera_frame_provider=( - session_recorded_camera_frame_service.extract - if session_recorded_camera_frame_service is not None - else None - ), - jobs_root=REPOSITORY_ROOT / ".runtime" / "compute-jobs", - rerun_overlay_cache_root=(session_store.data_dir / "laboratory-rerun-overlays"), - ffmpeg_path=_ffmpeg, - ) -) -app.include_router( - build_vegetation_benchmark_lab_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "lab-v1-vegetation-benchmark" - / "results" - ), - ) -) -app.include_router( - build_m49_physical_safety_playback_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m49" - / "physical-safety-playback-results" - ), - ) -) -app.include_router( - build_m48s_fixed_class_detector_lab_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m48s-semantic-shadow" - / "fixed-class-detector-lab-results" - ), - repository_root_provider=lambda: REPOSITORY_ROOT, - camera_frame_provider=( - session_recorded_camera_frame_service.extract - if session_recorded_camera_frame_service is not None - else None - ), - ) -) -app.include_router( - build_m48t_risk_quality_lab_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m48t-risk-quality" - / "lab-results" - ), - native_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "m48t-risk-quality" - / "native-lab-results" - ), - ) -) -app.include_router( - build_e47_semantic_slam_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e47" / "semantic-slam-results" - ), - ) -) -app.include_router( - build_e46e_ready_stack_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46e" / "ready-stack-results" - ), - ) -) -app.include_router( - build_e46f_dashcam_bakeoff_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "e46f" - / "dashcam-bakeoff-results" - ), - e46e_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46e" / "ready-stack-results" - ), - ) -) -app.include_router( - build_e46g_rectified_detector_bakeoff_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46g" / "results" - ) - ) -) -app.include_router( - build_e46h_full_rectified_front_replay_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46h" / "results" - ) - ) -) -app.include_router( - build_e46i_grounding_dino_full_replay_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46i" / "results" - ) - ) -) -app.include_router( - build_e46j_raw_fisheye_realtime_router( - root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46j" / "results" - ) - ) -) -app.include_router( - build_l34_annotation_router( - root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - annotation_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "laboratory-annotations" / "l34" - ), - ) -) -app.include_router( - build_l34a_assisted_yolox_error_audit_router( - audit_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "assisted-yolox-error-audits" - ), - l34_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - ) -) -app.include_router( - build_l34b_nested_box_consolidation_router( - shadow_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "nested-box-consolidation-shadows" - ), - l34_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - ) -) -app.include_router( - build_l34c_tile_seam_stitch_router( - shadow_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "tile-seam-stitch-shadows" - ), - l34_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - ) -) -app.include_router( - build_l34d_cumulative_postprocessing_router( - candidate_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "cumulative-postprocessing-candidates" - ), - l34_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - ) -) -app.include_router( - build_l34d_blind_annotation_router( - candidate_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "cumulative-postprocessing-candidates" - ), - l34_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - annotation_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "laboratory-annotations" / "l34d-blind" - ), - ) -) -app.include_router( - build_l34e_self_review_diagnostic_router( - diagnostic_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "self-review-diagnostics" - ), - candidate_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "cumulative-postprocessing-candidates" - ), - l34_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - ) -) -app.include_router( - build_l34f_adjudication_router( - diagnostic_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "self-review-diagnostics" - ), - candidate_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "cumulative-postprocessing-candidates" - ), - l34_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "l3" - / "right-yolox-truth-island-freeze" - ), - truth_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e46" / "results" - ), - evaluation_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" - ), - adjudication_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "laboratory-annotations" / "l34f-adjudication" - ), - result_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "l3" / "adjudicated-references" - ), - ) -) -app.include_router( - build_e30_review_router( - materialization_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "materializations" - ), - review_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "review-packs" - ), - ) -) -app.include_router( - build_e40_case_review_router( - e40_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e40" / "results" - ), - operator_review_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e40" / "operator-reviews" - ), - ) -) -app.include_router( - build_e30_engineering_router( - generation_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "engineering-generations" - ), - materialization_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "materializations" - ), - review_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "review-packs" - ), - ) -) -app.include_router( - build_e30_human_review_router( - materialization_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "materializations" - ), - review_pack_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "review-packs" - ), - engineering_generation_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "engineering-generations" - ), - draft_root_provider=lambda: ( - REPOSITORY_ROOT / ".runtime" / "compute-experiments" / "e30" / "human-review-drafts" - ), - generation_root_provider=lambda: ( - REPOSITORY_ROOT - / ".runtime" - / "compute-experiments" - / "e30" - / "human-review-generations" - ), - ) + build_laboratory_worker_gateway_router(laboratory_worker_gateway, namespace="lidar") ) app.include_router( build_system_telemetry_router( @@ -2011,7 +1162,6 @@ app.include_router( service=simulation_project_service, ) ) -app.include_router(build_scene_profiles_router(lambda: session_store.data_dir / "scene-profiles")) frontend_dist = REPOSITORY_ROOT / "apps" / "control-station" / "dist" try: app.include_router(build_ai_polygon_router(session_store.data_dir, OBSERVATORY_RECORDED_JOB_QUEUE)) diff --git a/src/k1link/web/local_storage_api.py b/src/k1link/web/local_storage_api.py new file mode 100644 index 00000000..cc6938db --- /dev/null +++ b/src/k1link/web/local_storage_api.py @@ -0,0 +1,49 @@ +"""Operator policy and explicit management of reproducible presentation copies.""" + +from typing import Annotated + +from fastapi import APIRouter, HTTPException, Path +from pydantic import BaseModel, ConfigDict, Field + +from k1link.laboratory.local_presentations import LocalPresentationError, LocalPresentations + + +class RetentionPolicy(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + retention_days: int = Field(ge=1, le=365) + + +class PinCopy(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + pinned: bool + + +CopyId = Annotated[str, Path(min_length=1, max_length=200, pattern=r"^[a-zA-Z0-9._:-]+$")] + + +def build_local_storage_router(store: LocalPresentations) -> APIRouter: + router = APIRouter(prefix="/api/v1/storage/laboratory", tags=["storage"]) + + def invoke(action): + try: + return action() + except (LocalPresentationError, OSError, ValueError) as exc: + raise HTTPException(409, str(exc)) from exc + + @router.get("") + def snapshot(): + return invoke(store.snapshot) + + @router.put("/policy") + def policy(value: RetentionPolicy): + return invoke(lambda: store.policy(value.retention_days)) + + @router.put("/copies/{result_id}/pin") + def pin(result_id: CopyId, value: PinCopy): + return invoke(lambda: store.pin(result_id, value.pinned)) + + @router.delete("/copies/{result_id}") + def remove(result_id: CopyId): + return invoke(lambda: store.remove(result_id)) + + return router diff --git a/src/k1link/web/modular_observatory_api.py b/src/k1link/web/modular_observatory_api.py index acc81bfe..cc3efb58 100644 --- a/src/k1link/web/modular_observatory_api.py +++ b/src/k1link/web/modular_observatory_api.py @@ -7,6 +7,7 @@ from typing import Any from fastapi import APIRouter, HTTPException, Query, Response from pydantic import BaseModel, ConfigDict, Field +from k1link.laboratory.data_deletion import LabDeletionError from k1link.observatory.composition_runs import ( CompositionRun, CompositionRunError, @@ -31,8 +32,10 @@ from k1link.observatory.portable_queue_binding import ( from k1link.observatory.portable_run_definitions import PortableRunDefinitionRegistry from k1link.observatory.recorded_jobs import ( ObservatoryRecordedJobQueue, + ObservatoryRecordedQueueConflictError, ObservatoryRecordedQueueDuplicateError, ObservatoryRecordedQueueError, + ObservatoryRecordedQueueNotFoundError, ) from k1link.observatory.source_admission import PortableSourceNotPreparedError from k1link.sessions import SessionNotFoundError, SessionStore @@ -118,6 +121,7 @@ def build_modular_observatory_router( binding: PortableRecordedQueueBindingService | None = None, queue: ObservatoryRecordedJobQueue | None = None, view_profiles: LabViewProfileStore | None = None, + deletion_service=None, ) -> APIRouter: router = APIRouter() @@ -391,6 +395,8 @@ def build_modular_observatory_router( except ( CompositionRunError, ObservatoryRecordedQueueError, + ObservatoryRecordedQueueNotFoundError, + ObservatoryRecordedQueueConflictError, ObservatoryOntologyError, ValueError, ) as exc: @@ -427,9 +433,31 @@ def build_modular_observatory_router( if composition_runs is None: raise HTTPException(503, "Композиции AI-слоя недоступны.") try: - composition_runs.delete_projection(run_id) - except CompositionRunError as exc: - raise HTTPException(404, "Результат AI Inference не найден.") from exc + if deletion_service is None: + raise HTTPException(503, "Полное удаление LAB пока недоступно.") + deletion_service.delete("composition", run_id) + except (LabDeletionError, CompositionRunError) as exc: + raise HTTPException(409, str(exc)) from exc + return Response(status_code=204) + + @router.delete("/api/v1/observatory/ai-runs/{job_id}", status_code=204) + def delete_failed_run_projection(job_id: str) -> Response: + if queue is None: + raise HTTPException(503, "Очередь AI-слоёв недоступна.") + try: + if deletion_service is None: + raise HTTPException(503, "Полное удаление LAB пока недоступно.") + deletion_service.delete("job", job_id) + except LabDeletionError as exc: + raise HTTPException(409, str(exc)) from exc + except ObservatoryRecordedQueueNotFoundError as exc: + raise HTTPException(404, "Запуск не найден.") from exc + except ObservatoryRecordedQueueConflictError as exc: + raise HTTPException( + 409, "Удалить можно только завершённую ошибочную попытку без результата." + ) from exc + except ValueError as exc: + raise HTTPException(422, "Некорректный идентификатор запуска.") from exc return Response(status_code=204) @router.get("/api/v1/observatory/ai-runs") @@ -449,7 +477,8 @@ def build_modular_observatory_router( for job in queue.list_jobs( source_session_id=source_session_id, setup_id=setup_id, - limit=20, + limit=500, + include_hidden=False, ) ] except (ObservatoryRecordedQueueError, ValueError) as exc: @@ -457,7 +486,7 @@ def build_modular_observatory_router( jobs.sort(key=lambda job: job.created_at_utc, reverse=True) return { "schema_version": "missioncore.observatory-recorded-job-list/v1", - "items": [job.as_dict() for job in jobs[:20]], + "items": [job.as_dict() for job in jobs], "authority": { "commands_enabled": False, "actuation_allowed": False, diff --git a/src/k1link/web/observatory_api.py b/src/k1link/web/observatory_api.py index 3d7f8a33..f73b8e76 100644 --- a/src/k1link/web/observatory_api.py +++ b/src/k1link/web/observatory_api.py @@ -7,6 +7,7 @@ from fastapi import Path as ApiPath from fastapi.responses import JSONResponse from pydantic import BaseModel, ConfigDict, Field +from k1link.laboratory.data_deletion import LabDeletionError from k1link.observatory import ( LaboratorySetupRegistry, ObservatoryRunPreparationCapacityError, @@ -173,6 +174,7 @@ def build_observatory_router( portable_setup_projector: PortableSetupProjector | PortableLabV1SetupProjector | None = None, portable_setup_projector_error: str | None = None, portable_binding_service: PortableRecordedQueueBindingService | None = None, + deletion_service=None, portable_result_view: PortableResultViewService | None = None, portable_artifact_transport: PortableObservatoryArtifactTransport | None = None, portable_result_publisher: PortableObservatoryResultPublisher | None = None, @@ -1139,6 +1141,7 @@ def build_observatory_router( setup_id=setup_id, definition_sha256=definition_sha256, limit=limit, + include_hidden=False, ) except (ObservatoryRecordedQueueError, ValueError) as exc: raise HTTPException( @@ -1329,7 +1332,12 @@ def build_observatory_router( ) def delete_observatory_lab_projection(session_id: str) -> Response: try: - store.delete_capability_lab_projection(session_id) + if deletion_service is None: + store.validate_lab_projection(session_id) + raise HTTPException(503, "Полное удаление LAB пока недоступно.") + deletion_service.delete("lab", session_id) + except LabDeletionError as exc: + raise HTTPException(409, str(exc)) from exc except SessionNotFoundError as exc: raise HTTPException( status_code=404, diff --git a/src/k1link/web/observatory_worker_api.py b/src/k1link/web/observatory_worker_api.py index 8f14d535..139e2cc0 100644 --- a/src/k1link/web/observatory_worker_api.py +++ b/src/k1link/web/observatory_worker_api.py @@ -52,6 +52,8 @@ from k1link.observatory.recorded_jobs import ( RecordedExecutorIdentity, ) from k1link.observatory.recorded_progress import RecordedProgress +from k1link.observatory.transfer_space import TransferCapacityError +from k1link.web.source_transfer_response import SourceTransferFileResponse OBSERVATORY_WORKER_CAPABILITY_CLAIM_REQUEST_SCHEMA: Final = ( "missioncore.observatory-worker-claim-request/v2" @@ -67,9 +69,7 @@ OBSERVATORY_WORKER_SUCCEED_REQUEST_SCHEMA: Final = ( OBSERVATORY_WORKER_FAIL_REQUEST_SCHEMA: Final = "missioncore.observatory-worker-fail-request/v1" OBSERVATORY_WORKER_CONTOUR_HEADER: Final = "X-Mission-Core-Contour-Id" OBSERVATORY_WORKER_CLAIM_TOKEN_HEADER: Final = "X-Mission-Core-Claim-Token" -OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER: Final = ( - "X-Mission-Core-Claim-Generation" -) +OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER: Final = "X-Mission-Core-Claim-Generation" _IDENTIFIER = re.compile(r"^[a-z][a-z0-9-]{2,95}$") _SHA256 = re.compile(r"^[a-f0-9]{64}$") @@ -175,8 +175,7 @@ class ObservatoryWorkerClaimRequest(_StrictWorkerRequest): @model_validator(mode="after") def validate_capability_snapshot(self) -> ObservatoryWorkerClaimRequest: identities = tuple( - capability.recorded_identity() - for capability in self.supported_executor_identities + capability.recorded_identity() for capability in self.supported_executor_identities ) if len(identities) != len(set(identities)): raise ValueError("executor capabilities must be unique") @@ -306,11 +305,14 @@ def build_observatory_worker_router( ) ) if claim is None: - return Response(status_code=204, headers={ - "X-Mission-Core-Idle-Claim": ( - "non-binding" if request.schema_version.endswith("/v3") else "durable" - ), - }) + return Response( + status_code=204, + headers={ + "X-Mission-Core-Idle-Claim": ( + "non-binding" if request.schema_version.endswith("/v3") else "durable" + ), + }, + ) return claim.as_dict() @router.get("/recorded-jobs/{job_id}") @@ -345,10 +347,14 @@ def build_observatory_worker_router( request: ObservatoryWorkerProgressRequest, job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)], ) -> Response: - _queue_call(lambda: queue.report_progress( - job_id, claim_token=request.claim_token, - claimant_id=authentication.contour_id, progress=request.progress, - )) + _queue_call( + lambda: queue.report_progress( + job_id, + claim_token=request.claim_token, + claimant_id=authentication.contour_id, + progress=request.progress, + ) + ) return Response(status_code=204) @router.post("/recorded-jobs/{job_id}/checkpoint") @@ -434,9 +440,7 @@ def build_observatory_worker_router( status_code=409, detail="Recorded result is not awaiting publication.", ) - package_root = _artifact_call( - lambda: artifact_transport.package_root_for_terminal(job) - ) + package_root = _artifact_call(lambda: artifact_transport.package_root_for_terminal(job)) try: result_publisher.publish(job=job, package_root=package_root) except PortableResultPublisherError as exc: @@ -487,8 +491,7 @@ def build_observatory_worker_router( claim_token=claim_token, claim_generation=claim_generation, claimant_id=authentication.contour_id, - ) - .as_dict() + ).as_dict() ) @router.get("/recorded-jobs/{job_id}/source-camera-epoch-archive") @@ -506,25 +509,32 @@ def build_observatory_worker_router( Header(alias=OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER, ge=1), ], ) -> FileResponse: - archive, path = _artifact_call( - lambda: artifact_transport.materialize_camera_epoch_archive( - job_id=job_id, - claim_token=claim_token, - claim_generation=claim_generation, - claimant_id=authentication.contour_id, + lease_fd = artifact_transport.source_lifecycle.acquire_reader() + try: + archive, path = _artifact_call( + lambda: artifact_transport.materialize_camera_epoch_archive( + job_id=job_id, + claim_token=claim_token, + claim_generation=claim_generation, + claimant_id=authentication.contour_id, + ) ) - ) - return FileResponse( - path, - media_type=PORTABLE_CAMERA_EPOCH_ARCHIVE_MEDIA_TYPE, - headers={ - "ETag": f'"{archive.sha256}"', - "Cache-Control": "private, no-store", - "X-Content-Type-Options": "nosniff", - "X-Mission-Core-Content-Sha256": archive.sha256, - PORTABLE_CAMERA_EPOCH_ARCHIVE_ID_HEADER: archive.archive_id, - }, - ) + response = SourceTransferFileResponse( + path, + media_type=PORTABLE_CAMERA_EPOCH_ARCHIVE_MEDIA_TYPE, + headers={ + "ETag": f'"{archive.sha256}"', + "Cache-Control": "private, no-store", + "X-Content-Type-Options": "nosniff", + "X-Mission-Core-Content-Sha256": archive.sha256, + PORTABLE_CAMERA_EPOCH_ARCHIVE_ID_HEADER: archive.archive_id, + }, + ) + response.lease_fd = lease_fd + return response + except BaseException: + os.close(lease_fd) + raise @router.get("/recorded-jobs/{job_id}/source-members/{member_id}") def source_member( @@ -542,29 +552,34 @@ def build_observatory_worker_router( Header(alias=OBSERVATORY_WORKER_CLAIM_GENERATION_HEADER, ge=1), ], ) -> FileResponse: - member, path = _artifact_call( - lambda: artifact_transport.materialize_source_member( - job_id=job_id, - member_id=member_id, - claim_token=claim_token, - claim_generation=claim_generation, - claimant_id=authentication.contour_id, + lease_fd = artifact_transport.source_lifecycle.acquire_reader() + try: + member, path = _artifact_call( + lambda: artifact_transport.materialize_source_member( + job_id=job_id, + member_id=member_id, + claim_token=claim_token, + claim_generation=claim_generation, + claimant_id=authentication.contour_id, + ) ) - ) - return FileResponse( - path, - media_type=member.media_type, - headers={ - "ETag": f'"{member.sha256}"', - "Cache-Control": "private, no-store", - "X-Content-Type-Options": "nosniff", - "X-Mission-Core-Content-Sha256": member.sha256, - }, - ) + response = SourceTransferFileResponse( + path, + media_type=member.media_type, + headers={ + "ETag": f'"{member.sha256}"', + "Cache-Control": "private, no-store", + "X-Content-Type-Options": "nosniff", + "X-Mission-Core-Content-Sha256": member.sha256, + }, + ) + response.lease_fd = lease_fd + return response + except BaseException: + os.close(lease_fd) + raise - @router.put( - "/recorded-jobs/{job_id}/result-packages/{result_sha256}/manifest" - ) + @router.put("/recorded-jobs/{job_id}/result-packages/{result_sha256}/manifest") async def stage_result_manifest( request: Request, job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)], @@ -590,13 +605,10 @@ def build_observatory_worker_router( claim_token=claim_token, claim_generation=claim_generation, claimant_id=authentication.contour_id, - ) - .as_dict() + ).as_dict() ) - @router.put( - "/recorded-jobs/{job_id}/result-packages/{result_sha256}/members/{member_id}" - ) + @router.put("/recorded-jobs/{job_id}/result-packages/{result_sha256}/members/{member_id}") async def upload_result_member( request: Request, job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)], @@ -628,9 +640,7 @@ def build_observatory_worker_router( _raise_artifact_or_queue_error(exc) return plan.as_dict() - @router.post( - "/recorded-jobs/{job_id}/result-packages/{result_sha256}/complete" - ) + @router.post("/recorded-jobs/{job_id}/result-packages/{result_sha256}/complete") def complete_result_package( job_id: Annotated[str, ApiPath(pattern=_JOB_ID_PATTERN)], result_sha256: Annotated[str, ApiPath(pattern=r"^[a-f0-9]{64}$")], @@ -653,8 +663,7 @@ def build_observatory_worker_router( claim_token=claim_token, claim_generation=claim_generation, claimant_id=authentication.contour_id, - ) - .as_dict() + ).as_dict() ) return router @@ -717,6 +726,10 @@ def _queue_call[T](operation: Callable[[], T]) -> T: def _artifact_call[T](operation: Callable[[], T]) -> T: try: return _queue_call(operation) + except TransferCapacityError as exc: + raise HTTPException( + status_code=503, detail=str(exc), headers={"Retry-After": "30"} + ) from exc except PortableArtifactTransportIntegrityError as exc: raise HTTPException( status_code=409, @@ -735,6 +748,10 @@ def _artifact_call[T](operation: Callable[[], T]) -> T: def _raise_artifact_or_queue_error(exc: Exception) -> None: + if isinstance(exc, TransferCapacityError): + raise HTTPException( + status_code=503, detail=str(exc), headers={"Retry-After": "30"} + ) from exc if isinstance(exc, PortableArtifactTransportIntegrityError): raise HTTPException( status_code=409, diff --git a/src/k1link/web/portable_replay_api.py b/src/k1link/web/portable_replay_api.py index 28fe5865..6e792f03 100644 --- a/src/k1link/web/portable_replay_api.py +++ b/src/k1link/web/portable_replay_api.py @@ -9,6 +9,7 @@ from fastapi import APIRouter, HTTPException, Path, Query, Response from fastapi.responses import FileResponse from k1link.laboratory.canonical_rerun_overlay import CanonicalLabOverlayError +from k1link.laboratory.local_presentations import LOCK as PRESENTATION_LOCK from k1link.observatory.composition_runs import CompositionRunError, CompositionRunStore from k1link.observatory.portable_replay import PortableReplayService from k1link.observatory.portable_result_view import PortableResultViewError @@ -39,6 +40,42 @@ def build_portable_replay_router( router = APIRouter(tags=["observatory"]) path = "/api/v1/observatory/portable-results/{result_id}/replays/{base_sha}/recording.rrd" + class LeasedReplayResponse(FileResponse): + def __init__(self, artifact, result_id): + self.copy_id = result_id + self.copies = getattr(service, "local_copies", None) + super().__init__( + artifact.path, + media_type="application/vnd.rerun.rrd", + headers={ + "ETag": f'"{artifact.sha256}"', + "X-Rerun-Format": "RRF2", + "Cache-Control": "private, max-age=31536000, immutable", + "X-Content-Type-Options": "nosniff", + }, + ) + if self.copies is not None: + self.copies.acquire(result_id) + + async def __call__(self, scope, receive, send): + try: + await super().__call__(scope, receive, send) + finally: + if self.copies is not None: + self.copies.release(self.copy_id) + + def read_copy(copy_id, generation, getter): + with PRESENTATION_LOCK: + try: + artifact = getter() + except (ValueError, OSError, KeyError, TypeError, PortableResultViewError) as exc: + raise HTTPException(409, "Кэш результата не прошёл проверку.") from exc + if artifact is None: + raise HTTPException(409, "Сохранённый просмотр ещё не подготовлен.") + if artifact.sha256 != generation: + raise HTTPException(412, "Версия сохранённого просмотра изменилась.") + return LeasedReplayResponse(artifact, copy_id) + @router.head(path) def prepare(result_id: ResultId, base_sha: BaseSha) -> Response: try: @@ -71,24 +108,7 @@ def build_portable_replay_router( base_sha: BaseSha, generation: Annotated[str, Query(pattern=r"^[a-f0-9]{64}$")], ) -> FileResponse: - try: - artifact = service.cached(result_id, base_sha) - except (ValueError, OSError, KeyError, TypeError, PortableResultViewError) as exc: - raise HTTPException(409, "Кэш результата не прошёл проверку.") from exc - if artifact is None: - raise HTTPException(409, "Сохранённый просмотр ещё не подготовлен.") - if artifact.sha256 != generation: - raise HTTPException(412, "Версия сохранённого просмотра изменилась.") - return FileResponse( - artifact.path, - media_type="application/vnd.rerun.rrd", - headers={ - "ETag": f'"{artifact.sha256}"', - "X-Rerun-Format": "RRF2", - "Cache-Control": "private, max-age=31536000, immutable", - "X-Content-Type-Options": "nosniff", - }, - ) + return read_copy(result_id, generation, lambda: service.cached(result_id, base_sha)) composition_path = ( "/api/v1/observatory/ai-composition-runs/{run_id}/replays/{base_sha}/recording.rrd" @@ -146,29 +166,10 @@ def build_portable_replay_router( base_sha: BaseSha, generation: Annotated[str, Query(pattern=r"^[a-f0-9]{64}$")], ) -> FileResponse: - try: - artifact = service.cached_composition(run_id, composition_members(run_id), base_sha) - except ( - ValueError, - OSError, - KeyError, - TypeError, - PortableResultViewError, - ) as exc: - raise HTTPException(409, "Кэш составного результата не прошёл проверку.") from exc - if artifact is None: - raise HTTPException(409, "Составной просмотр ещё не подготовлен.") - if artifact.sha256 != generation: - raise HTTPException(412, "Версия составного просмотра изменилась.") - return FileResponse( - artifact.path, - media_type="application/vnd.rerun.rrd", - headers={ - "ETag": f'"{artifact.sha256}"', - "X-Rerun-Format": "RRF2", - "Cache-Control": "private, max-age=31536000, immutable", - "X-Content-Type-Options": "nosniff", - }, + return read_copy( + run_id, + generation, + lambda: service.cached_composition(run_id, composition_members(run_id), base_sha), ) return router diff --git a/src/k1link/web/session_api.py b/src/k1link/web/session_api.py index 053c6ca8..d11ac169 100644 --- a/src/k1link/web/session_api.py +++ b/src/k1link/web/session_api.py @@ -21,6 +21,7 @@ from k1link.compute import ( RecordedPerceptionOverlayError, RecordedPerceptionVideo, ) +from k1link.laboratory.worker_gateway import LaboratoryWorkerGateway from k1link.sessions import ( LayoutConflictError, MaterializedRecording, @@ -398,6 +399,7 @@ def build_session_router( media_inspector: RecordedMediaInspector | None = None, perception_overlay_provider: RecordedPerceptionOverlayProvider | None = None, perception_media_provider: RecordedPerceptionMediaProvider | None = None, + laboratory_gateway: LaboratoryWorkerGateway | None = None, point_color_renderers: Mapping[str, RecordedPointColorRenderer] | None = None, point_display_renderers: Mapping[str, RecordedPointDisplayRenderer] | None = None, lab_calculation_profile_resolver: ( @@ -411,6 +413,38 @@ def build_session_router( router = APIRouter(tags=["observation-sessions"]) recorded_media_inspector = media_inspector or RecordedMediaInspector() + def perception_route(path: str, *, methods=None): + """Bind Core to Worker while retaining the existing presentation contracts.""" + def decorate(handler): + if laboratory_gateway is None: + return router.api_route(path, methods=methods or ["GET"])(handler) + + async def forward(request: Request, session_id: str): + try: + command = await run_in_threadpool( + _prepare_replay, store, catalog_refresher, + session_id, 1.0, False, False, + ) + if request.method == "POST" and command.map_version is not None: + raise HTTPException( + 409, "Слой распознавания относится к исходной геометрии записи.") + except SessionNotFoundError as exc: + raise HTTPException(404, str(exc)) from exc + except (SessionNotReplayableError, SessionIntegrityError) as exc: + raise HTTPException(409, str(exc)) from exc + except ValueError as exc: + raise HTTPException(422, "Некорректный идентификатор сессии.") from exc + suffix = path.split("/{session_id}/", 1)[1] + for key, value in request.path_params.items(): + suffix = suffix.replace("{" + key + "}", str(value)) + return await laboratory_gateway.forward( + request, "presentation/sessions/" + session_id + "/" + suffix) + + forward.__name__ = handler.__name__ + "_worker" + router.add_api_route(path, forward, methods=methods or ["GET"]) + return handler + return decorate + @router.get("/api/v1/observation-sessions/{session_id}/display-profile") def get_session_display_profile(session_id: str): from k1link.sessions.display_profile import load_display_profile @@ -540,7 +574,9 @@ def build_session_router( ) async def delete_observation_session(session_id: str) -> Response: try: - store.get_session(session_id) + detail = store.get_session(session_id) + if detail.summary.lab is not None: + raise HTTPException(409, "Удалите LAB через её историю запусков.") recorded_artifacts = store.list_recorded_media(session_id) except SessionNotFoundError: # DELETE is idempotent. Multiple mounted catalogs or another @@ -1205,7 +1241,7 @@ def build_session_router( }, ) - @router.post("/api/v1/observation-sessions/{session_id}/perception.rrd") + @perception_route("/api/v1/observation-sessions/{session_id}/perception.rrd", methods=["POST"]) async def get_observation_session_perception( session_id: str, request: RecordedPerceptionRequest, @@ -1284,7 +1320,7 @@ def build_session_router( }, ) - @router.get("/api/v1/observation-sessions/{session_id}/perception/status") + @perception_route("/api/v1/observation-sessions/{session_id}/perception/status") async def get_observation_session_perception_status( session_id: str, response: Response, @@ -1458,7 +1494,7 @@ def build_session_router( return StreamingResponse(chunks(), media_type="application/vnd.nodedc.point-display-stream", headers={"Cache-Control": "no-store, no-transform"}) - @router.get("/api/v1/observation-sessions/{session_id}/perception-media/{result_id}/manifest") + @perception_route("/api/v1/observation-sessions/{session_id}/perception-media/{result_id}/manifest") def get_recorded_perception_media_manifest( session_id: str, result_id: str, @@ -1482,7 +1518,7 @@ def build_session_router( }, ) - @router.api_route( + @perception_route( "/api/v1/observation-sessions/{session_id}/perception-media/{result_id}/recording.mp4", methods=["GET", "HEAD"], ) diff --git a/src/k1link/web/source_transfer_response.py b/src/k1link/web/source_transfer_response.py new file mode 100644 index 00000000..9acc086a --- /dev/null +++ b/src/k1link/web/source_transfer_response.py @@ -0,0 +1,21 @@ +"""Keep source-copy readers alive through streaming, ranges and disconnects.""" + +import os + +from starlette.responses import FileResponse +from starlette.types import Receive, Scope, Send + + +class SourceTransferFileResponse(FileResponse): + lease_fd: int + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + # The response owns the read. Do not delegate pathsend to a server which + # could open the pathname after this coroutine has released its lease. + extensions = dict(scope.get("extensions", {})) + extensions.pop("http.response.pathsend", None) + scope = {**scope, "extensions": extensions} + try: + await super().__call__(scope, receive, send) + finally: + os.close(self.lease_fd) diff --git a/src/k1link/web/worker_laboratory_presentation.py b/src/k1link/web/worker_laboratory_presentation.py new file mode 100644 index 00000000..50f51aa1 --- /dev/null +++ b/src/k1link/web/worker_laboratory_presentation.py @@ -0,0 +1,129 @@ +"""Full recorded perception playback prepared exclusively in the Worker volume.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Annotated + +from fastapi import APIRouter, Header, HTTPException, Query, Request +from fastapi.responses import FileResponse, JSONResponse, Response + +from k1link.compute import ( + IntegratedPerceptionOverlayStore, + RecordedCalibratedFusionStore, + RecordedPerceptionEpochStore, + RecordedPerceptionOverlayMux, + RecordedPerceptionOverlayStore, +) +from k1link.compute.results import RecordedPerceptionOverlayArtifact +from k1link.web.session_api import ( + RecordedPerceptionPreparationStatus, + RecordedPerceptionRequest, + _recorded_perception_manifest_document, + _recorded_perception_video_response, + _require_matching_digest, +) + + +def build_worker_laboratory_presentation(root: Path, ffmpeg: Path) -> APIRouter: + router = APIRouter(prefix="/api/v1/laboratory/presentation/sessions") + jobs = root / ".runtime/compute-jobs" + results = root / ".runtime/compute-results" + cache = root / "presentation" + legacy = RecordedPerceptionOverlayStore( + jobs_root=jobs, + results_root=results, + cache_root=cache / "perception-overlays", + ffmpeg_path=ffmpeg, + ffprobe_path=ffmpeg.with_name("ffprobe"), + ) + fusion = RecordedCalibratedFusionStore( + jobs_root=jobs, + perception_results_root=results, + fusion_results_root=root / ".runtime/compute-fusions", + cache_root=cache / "calibrated-fusion-overlays", + ) + integrated = IntegratedPerceptionOverlayStore( + jobs_root=jobs, + results_root=root / ".runtime/compute-experiments/e10/worker-results", + lidar_packs_root=root / ".runtime/compute-experiments/e10/lidar-packs", + cache_root=cache / "integrated-perception-overlays", + ffmpeg_path=ffmpeg, + ) + overlay = RecordedPerceptionOverlayMux(integrated, RecordedPerceptionOverlayMux(fusion, legacy)) + media = RecordedPerceptionEpochStore( + jobs_root=jobs, + results_root=results, + ffprobe_path=ffmpeg.with_name("ffprobe"), + ) + + @router.post("/{session_id}/perception.rrd") + def recording(session_id: str, request: RecordedPerceptionRequest): + artifact = overlay.materialize(session_id, **request.model_dump()) + if artifact is None: + return Response(status_code=204, headers={"Cache-Control": "no-store"}) + if isinstance(artifact, RecordedPerceptionOverlayArtifact): + return FileResponse( + artifact.path, + media_type="application/vnd.rerun.rrd", + filename="perception.rrd", + content_disposition_type="inline", + headers={ + "ETag": f'"sha256:{artifact.sha256}"', + "Cache-Control": "private, no-cache, no-transform", + }, + ) + return Response( + artifact, + media_type="application/vnd.rerun.rrd", + headers={"Cache-Control": "private, no-cache, no-transform"}, + ) + + @router.get("/{session_id}/perception/status") + def status( + session_id: str, + recording_id: Annotated[ + str, Query(min_length=1, max_length=128, pattern=r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") + ], + ): + request = RecordedPerceptionRequest( + application_id="nodedc_mission_core_recorded", recording_id=recording_id + ) + return RecordedPerceptionPreparationStatus.model_validate( + overlay.status(session_id, recording_id=request.recording_id) + ) + + def video(session: str, result: str): + value = media.video(session, result) + if value is None: + raise HTTPException(404, "Готовое видео сегментации отсутствует.") + return value + + @router.get("/{session_id}/perception-media/{result_id}/manifest") + def manifest(session_id: str, result_id: str, if_match: str | None = Header(None)): + value = video(session_id, result_id) + etag = f'"sha256:{value.sha256}"' + _require_matching_digest(etag, if_match) + return JSONResponse( + _recorded_perception_manifest_document(value), + headers={"ETag": etag, "Cache-Control": "private, no-cache"}, + ) + + @router.api_route( + "/{session_id}/perception-media/{result_id}/recording.mp4", methods=["GET", "HEAD"] + ) + def movie( + request: Request, + session_id: str, + result_id: str, + generation: str, + range_header: str | None = Header(None, alias="Range"), + ): + value = video(session_id, result_id) + if generation != value.sha256: + raise HTTPException(412, "Поколение видео сегментации было заменено.") + return _recorded_perception_video_response( + value, range_header, head_only=request.method == "HEAD" + ) + + return router diff --git a/src/k1link/web/worker_laboratory_surface.py b/src/k1link/web/worker_laboratory_surface.py new file mode 100644 index 00000000..6b5a804b --- /dev/null +++ b/src/k1link/web/worker_laboratory_surface.py @@ -0,0 +1,890 @@ +"""Worker-owned legacy LAB presentation and evaluation surface. + +Existing evidence validators and projections are reused unchanged. Only the +Worker composes this filesystem-backed surface; the operator uses its transport. +The legacy runtime layout is a compatibility binding inside a managed volume, +not an operator checkout or a reason to copy compute inputs to the operator. +""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + +from fastapi import APIRouter + +from k1link.laboratory import ( + LaboratoryEvidenceRegistry, + LaboratoryEvidenceReportService, + LaboratoryRunner, + LaboratoryValueReviewRegistry, +) +from k1link.laboratory.m48_raw_evidence import ( + M48_EXPECTED_THREAT_RESULT_ID, + M48RawEvidenceError, + M48RawEvidenceReader, +) +from k1link.sessions import RecordedCameraFrame +from k1link.web.advanced_laboratory_api import build_advanced_laboratory_router +from k1link.web.e30_engineering_api import build_e30_engineering_router +from k1link.web.e30_human_review_api import build_e30_human_review_router +from k1link.web.e30_review_api import build_e30_review_router +from k1link.web.e40_case_review_api import build_e40_case_review_router +from k1link.web.e46_blind_review_api import build_e46_blind_review_router +from k1link.web.e46a_ai_engineering_preannotation_api import ( + build_e46a_ai_engineering_preannotation_router, +) +from k1link.web.e46b_temporal_motion_api import build_e46b_temporal_motion_router +from k1link.web.e46c_full_replay_world_tracks_api import build_e46c_full_replay_world_tracks_router +from k1link.web.e46d_temporal_failure_audit_api import build_e46d_temporal_failure_audit_router +from k1link.web.e46e_ready_stack_api import build_e46e_ready_stack_router +from k1link.web.e46f_dashcam_bakeoff_api import build_e46f_dashcam_bakeoff_router +from k1link.web.e46g_rectified_detector_bakeoff_api import ( + build_e46g_rectified_detector_bakeoff_router, +) +from k1link.web.e46h_full_rectified_front_replay_api import ( + build_e46h_full_rectified_front_replay_router, +) +from k1link.web.e46i_grounding_dino_full_replay_api import ( + build_e46i_grounding_dino_full_replay_router, +) +from k1link.web.e46j_raw_fisheye_realtime_api import build_e46j_raw_fisheye_realtime_router +from k1link.web.e47_semantic_slam_api import build_e47_semantic_slam_router +from k1link.web.l3_pointpillars_visual_api import build_l3_pointpillars_visual_router +from k1link.web.l31_pointpillars_ravnoves_api import build_l31_pointpillars_ravnoves_router +from k1link.web.l32_pointpillars_camera_review_api import ( + build_l32_pointpillars_camera_review_router, +) +from k1link.web.l33_camera_first_detector_review_api import ( + build_l33_camera_first_detector_review_router, +) +from k1link.web.l34_annotation_api import ( + build_l34_annotation_router, + build_l34d_blind_annotation_router, +) +from k1link.web.l34_right_yolox_truth_island_api import ( + build_l34_right_yolox_truth_island_freeze_router, +) +from k1link.web.l34a_assisted_yolox_error_audit_api import ( + build_l34a_assisted_yolox_error_audit_router, +) +from k1link.web.l34b_nested_box_consolidation_api import build_l34b_nested_box_consolidation_router +from k1link.web.l34c_tile_seam_stitch_api import build_l34c_tile_seam_stitch_router +from k1link.web.l34d_cumulative_postprocessing_api import ( + build_l34d_cumulative_postprocessing_router, +) +from k1link.web.l34e_self_review_diagnostic_api import build_l34e_self_review_diagnostic_router +from k1link.web.l34f_adjudication_api import build_l34f_adjudication_router +from k1link.web.laboratory_api import build_laboratory_router +from k1link.web.laboratory_report_api import build_laboratory_report_router +from k1link.web.m4_threat_replay_api import build_m4_threat_replay_router +from k1link.web.m48_object_quality_api import build_m48_object_quality_router +from k1link.web.m48r3_static_occupancy_api import build_m48r3_static_occupancy_router +from k1link.web.m48s_fixed_class_detector_lab_api import build_m48s_fixed_class_detector_lab_router +from k1link.web.m48t_risk_quality_lab_api import build_m48t_risk_quality_lab_router +from k1link.web.m49_physical_safety_playback_api import build_m49_physical_safety_playback_router +from k1link.web.m49_tgs_fail_closed_api import build_m49_tgs_fail_closed_router +from k1link.web.m49_tgs_full_shadow_api import build_m49_tgs_full_shadow_router +from k1link.web.vegetation_shadow_lab_api import ( + build_vegetation_benchmark_lab_router, + build_vegetation_shadow_lab_router, +) + + +def build_worker_laboratory_router( + *, + repository_root: Path, + configuration_root: Path, + presentation_root: Path, + camera_frame_provider: Callable[[str, int], RecordedCameraFrame] | None = None, + camera_playback_provider: Callable | None = None, + canonical_recording_provider: Callable[[str], tuple[Path, str] | None] | None = None, + ffmpeg_path: Path | None = None, + evaluation_runner: LaboratoryRunner | None = None, +) -> APIRouter: + """Compose identical LAB routes against Worker-owned evidence and result roots.""" + router = APIRouter() + evidence_registry = LaboratoryEvidenceRegistry.from_directory( + configuration_root / "laboratories" + ) + value_registry = LaboratoryValueReviewRegistry.from_file( + configuration_root / "laboratory-value-review.json" + ) + reports = LaboratoryEvidenceReportService( + evidence_registry, lambda: repository_root / ".runtime" / "compute-experiments" + ) + try: + raw_evidence = M48RawEvidenceReader.from_repository( + repository_root=repository_root, + threat_result_root=repository_root + / ".runtime/compute-experiments/m4/replay-threat" + / M48_EXPECTED_THREAT_RESULT_ID, + ) + except (M48RawEvidenceError, OSError, ValueError): + raw_evidence = None + + router.include_router( + build_laboratory_router( + e29_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e29" / "results" + ), + local_surface_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "k1-local-surface-v1" + / "models" + ), + source_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e10" / "lidar-packs" + ), + source_result_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e10" / "worker-results" + ), + ) + ) + + router.include_router( + build_laboratory_report_router( + value_registry, + reports, + ) + ) + + router.include_router( + build_advanced_laboratory_router( + evidence_registry=evidence_registry, + evidence_runtime_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" + ), + e31_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e31" + / "source-qualifications" + ), + e32_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e32" / "results" + ), + e33_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e33" / "results" + ), + e34_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e34" / "results" + ), + e35_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e35" / "results" + ), + e37_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e37" / "results" + ), + e38_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e38" / "results" + ), + e39_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e39" / "results" + ), + e40_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e40" / "results" + ), + l3_visual_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "l3" / "visual-audits" + ), + l31_ravnoves_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "pointpillars-ravnoves" + ), + l32_camera_review_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "pointpillars-camera-review" + ), + l33_camera_first_review_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "camera-first-detector-review" + ), + ) + ) + + router.include_router( + build_l3_pointpillars_visual_router( + root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "l3" / "visual-audits" + ) + ) + ) + + router.include_router( + build_l31_pointpillars_ravnoves_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "pointpillars-ravnoves" + ) + ) + ) + + router.include_router( + build_l32_pointpillars_camera_review_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "pointpillars-camera-review" + ) + ) + ) + + router.include_router( + build_l33_camera_first_detector_review_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "camera-first-detector-review" + ) + ) + ) + + router.include_router( + build_l34_right_yolox_truth_island_freeze_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + ) + ) + + router.include_router( + build_e46_blind_review_router( + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + annotation_root_provider=lambda: ( + repository_root / ".runtime" / "laboratory-annotations" / "e46-blind" + ), + submission_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e48" / "review-submissions" + ), + ) + ) + + router.include_router( + build_e46a_ai_engineering_preannotation_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e46a" + / "ai-engineering-preannotations" + ), + annotation_root_provider=lambda: ( + repository_root / ".runtime" / "laboratory-annotations" / "e46a-correction" + ), + ) + ) + + router.include_router( + build_e46b_temporal_motion_router( + root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46b" / "temporal-motion" + ), + ) + ) + + router.include_router( + build_e46c_full_replay_world_tracks_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e46c" + / "full-replay-world-tracks" + ), + e26_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e10" / "worker-results" + ), + ) + ) + + router.include_router( + build_e46d_temporal_failure_audit_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e46d" + / "temporal-failure-audits" + ), + ) + ) + + router.include_router( + build_m4_threat_replay_router( + root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "m4" / "replay-threat" + ), + repository_root_provider=lambda: repository_root, + camera_frame_provider=( + camera_frame_provider if camera_frame_provider is not None else None + ), + ) + ) + + router.include_router( + build_m48_object_quality_router( + pack_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48" + / "object-quality-packs" + ), + workflow_root_provider=lambda: ( + repository_root / ".runtime" / "laboratory-annotations" / "m48-object-quality" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "m48" / "object-truth-seals" + ), + result_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48" + / "object-quality-results" + ), + small_static_result_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48" + / "small-static-passage-regression-results" + ), + static_occupancy_result_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48" + / "static-occupancy-qualification-results" + ), + camera_frame_provider=( + camera_frame_provider if camera_frame_provider is not None else None + ), + camera_playback_provider=(camera_playback_provider), + spatial_evidence_provider=raw_evidence, + evaluation_runner=evaluation_runner, + evaluation_receipt_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "laboratory-run-receipts" + ), + ) + ) + + router.include_router( + build_m48r3_static_occupancy_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48" + / "static-occupancy-shadow-results" + ), + repository_root_provider=lambda: repository_root, + camera_frame_provider=( + camera_frame_provider if camera_frame_provider is not None else None + ), + ) + ) + + router.include_router( + build_m49_tgs_fail_closed_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m49" + / "tgs-fail-closed-results" + ), + ) + ) + + router.include_router( + build_m49_tgs_full_shadow_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m49" + / "tgs-full-shadow-results" + ), + ) + ) + + router.include_router( + build_vegetation_shadow_lab_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "lab-v1-vegetation" + / "results" + ), + canonical_recording_provider=canonical_recording_provider, + camera_frame_provider=( + camera_frame_provider if camera_frame_provider is not None else None + ), + jobs_root=repository_root / ".runtime" / "compute-jobs", + rerun_overlay_cache_root=(presentation_root / "laboratory-rerun-overlays"), + ffmpeg_path=ffmpeg_path, + ) + ) + + router.include_router( + build_vegetation_benchmark_lab_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "lab-v1-vegetation-benchmark" + / "results" + ), + ) + ) + + router.include_router( + build_m49_physical_safety_playback_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m49" + / "physical-safety-playback-results" + ), + ) + ) + + router.include_router( + build_m48s_fixed_class_detector_lab_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48s-semantic-shadow" + / "fixed-class-detector-lab-results" + ), + repository_root_provider=lambda: repository_root, + camera_frame_provider=( + camera_frame_provider if camera_frame_provider is not None else None + ), + ) + ) + + router.include_router( + build_m48t_risk_quality_lab_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48t-risk-quality" + / "lab-results" + ), + native_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "m48t-risk-quality" + / "native-lab-results" + ), + ) + ) + + router.include_router( + build_e47_semantic_slam_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e47" + / "semantic-slam-results" + ), + ) + ) + + router.include_router( + build_e46e_ready_stack_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e46e" + / "ready-stack-results" + ), + ) + ) + + router.include_router( + build_e46f_dashcam_bakeoff_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e46f" + / "dashcam-bakeoff-results" + ), + e46e_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e46e" + / "ready-stack-results" + ), + ) + ) + + router.include_router( + build_e46g_rectified_detector_bakeoff_router( + root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46g" / "results" + ) + ) + ) + + router.include_router( + build_e46h_full_rectified_front_replay_router( + root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46h" / "results" + ) + ) + ) + + router.include_router( + build_e46i_grounding_dino_full_replay_router( + root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46i" / "results" + ) + ) + ) + + router.include_router( + build_e46j_raw_fisheye_realtime_router( + root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46j" / "results" + ) + ) + ) + + router.include_router( + build_l34_annotation_router( + root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + annotation_root_provider=lambda: ( + repository_root / ".runtime" / "laboratory-annotations" / "l34" + ), + ) + ) + + router.include_router( + build_l34a_assisted_yolox_error_audit_router( + audit_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "assisted-yolox-error-audits" + ), + l34_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + ) + ) + + router.include_router( + build_l34b_nested_box_consolidation_router( + shadow_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "nested-box-consolidation-shadows" + ), + l34_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + ) + ) + + router.include_router( + build_l34c_tile_seam_stitch_router( + shadow_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "tile-seam-stitch-shadows" + ), + l34_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + ) + ) + + router.include_router( + build_l34d_cumulative_postprocessing_router( + candidate_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "cumulative-postprocessing-candidates" + ), + l34_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + ) + ) + + router.include_router( + build_l34d_blind_annotation_router( + candidate_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "cumulative-postprocessing-candidates" + ), + l34_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + annotation_root_provider=lambda: ( + repository_root / ".runtime" / "laboratory-annotations" / "l34d-blind" + ), + ) + ) + + router.include_router( + build_l34e_self_review_diagnostic_router( + diagnostic_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "self-review-diagnostics" + ), + candidate_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "cumulative-postprocessing-candidates" + ), + l34_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + ) + ) + + router.include_router( + build_l34f_adjudication_router( + diagnostic_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "self-review-diagnostics" + ), + candidate_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "cumulative-postprocessing-candidates" + ), + l34_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "right-yolox-truth-island-freeze" + ), + truth_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e46" / "results" + ), + evaluation_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e2" / "evaluation-packs" + ), + adjudication_root_provider=lambda: ( + repository_root / ".runtime" / "laboratory-annotations" / "l34f-adjudication" + ), + result_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "l3" + / "adjudicated-references" + ), + ) + ) + + router.include_router( + build_e30_review_router( + materialization_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e30" / "materializations" + ), + review_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e30" / "review-packs" + ), + ) + ) + + router.include_router( + build_e40_case_review_router( + e40_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e40" / "results" + ), + operator_review_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e40" / "operator-reviews" + ), + ) + ) + + router.include_router( + build_e30_engineering_router( + generation_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e30" + / "engineering-generations" + ), + materialization_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e30" / "materializations" + ), + review_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e30" / "review-packs" + ), + ) + ) + + router.include_router( + build_e30_human_review_router( + materialization_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e30" / "materializations" + ), + review_pack_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e30" / "review-packs" + ), + engineering_generation_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e30" + / "engineering-generations" + ), + draft_root_provider=lambda: ( + repository_root / ".runtime" / "compute-experiments" / "e30" / "human-review-drafts" + ), + generation_root_provider=lambda: ( + repository_root + / ".runtime" + / "compute-experiments" + / "e30" + / "human-review-generations" + ), + ) + ) + return router diff --git a/tests/fixtures/observatory/retired-fixed-lab/README.md b/tests/fixtures/observatory/retired-fixed-lab/README.md new file mode 100644 index 00000000..90c84e33 --- /dev/null +++ b/tests/fixtures/observatory/retired-fixed-lab/README.md @@ -0,0 +1,3 @@ +Frozen registry before retiring fixed LAB V1 on 2026-11-08. +Used only by compatibility/transport contract tests, never by production admission. +Current modular admission is tested separately. Shared models remain in config. diff --git a/tests/fixtures/observatory/retired-fixed-lab/observatory-portable-run-definitions.json b/tests/fixtures/observatory/retired-fixed-lab/observatory-portable-run-definitions.json new file mode 100644 index 00000000..36ecee49 --- /dev/null +++ b/tests/fixtures/observatory/retired-fixed-lab/observatory-portable-run-definitions.json @@ -0,0 +1 @@ +{"definitions":[{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"ddrnet-portable-runtime-config-v2","kind":"configuration","sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"component_id":"eomt-recorded-dependency-set-v1","kind":"dependency-set","sha256":"4eb1f8d33236806e74f9e5bb96b7dce2ac37623dc39b2184be2aa8d7d00e983e"},{"component_id":"eomt-recorded-orchestrator-v1","kind":"orchestrator","sha256":"d3e9435939444ab35b27a744ac314e289ebd66a13fa56e3d59f121e088d22774"},{"component_id":"eomt-recorded-profile-v1","kind":"profile","sha256":"ea583966bc3409f5cf563cbf4fad05e366907e67187082eb692aff53d9f5d875"},{"component_id":"eomt-recorded-runner-v1","kind":"runner","sha256":"1e64869de48d10f1531c742e6067c4c3ae2a709c5eb0d770d1fab74b4a2431ff"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"vegetation-mission-policy-v1","kind":"policy","sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"component_id":"vegetation-provider-label-map-v1","kind":"provider-map","sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"definition_id":"lab-v1-eomt-ddrnet-portable","definition_sha256":"269d71a24b4e63cff54e01273f9d4b35fc6cdd72bc6fadec206169ae0777e6ac","executor":{"contour_id":"worker-006","image_sha256":"5ad7d95baac63af13812cb693d492add4e806a333aba8e60edb2ea1aba754373","reason":null,"reason_code":null,"release_id":"lab-v1-installed-package-v1","release_sha256":"667858623962cd6d9849a8985b803f59e429916b5c56f76a6fc6c80c0c54526b","state":"ready"},"models":[{"architecture":"EomtForUniversalSegmentation","artifacts":[{"byte_length":1575,"role":"config-json","sha256":"7f4aa94fa4e43c0dbd79a5420edb511120aef62bd82bfbcbcece79948286a650"},{"byte_length":1276175488,"role":"model-weights","sha256":"c265da9a74f58f5c3f4826d23ca4ca78beac0b106cca5842beca61580de5b782"},{"byte_length":666,"role":"preprocessor-config","sha256":"97e2fbf7f0bdba2cfc90251c5133bae9c27ddc9c4410509f40670be2332854e7"}],"model_id":"tue-mps/cityscapes_semantic_eomt_large_1024","release_id":"eomt-cityscapes-large-1024-v1","revision":"8d6b6d1a3f7b50d441afd7d247c2ed10db186e8f"},{"architecture":"ddrnet_39","artifacts":[{"byte_length":259419077,"role":"checkpoint","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"}],"model_id":"goose-ddrnet-class-512","release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"recorded-eomt-ddrnet-review-v2","contract_sha256":"b3dfaa8e20a0f22fc510d062ac469f010a3281c650059d9ea134f0b3ccb38d9a","publication":"observatory","result_kind":"recorded-perception-qualification","result_schema":"missioncore.recorded-eomt-ddrnet-review/v2","schema_version":"missioncore.observatory-portable-result-contract/v2","version":2},"setup_id":"lab-v1-eomt-ddrnet-portable-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-observatory-v2","contract_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","version":2},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["point-cloud","trajectory","video"],"seekable":true},"version":2},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"m49-tgs-portable-profile-v2","kind":"configuration","sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"component_id":"m49-tgs-portable-runner-v1","kind":"runner","sha256":"e3bb2e91c70712eff74e8e69718075a407e042fb494616d65984500da42b21a9"}],"definition_id":"m49-tgs-portable","definition_sha256":"f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb","executor":{"contour_id":"worker-006","image_sha256":"f9278ab21aa65045be993dd19bffc25f49955e19598893ac78cc4761ca63ecf3","reason":null,"reason_code":null,"release_id":"m49-tgs-portable-executor-v1","release_sha256":"c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa","state":"ready"},"models":[],"resource_profile":{"accelerator_id":"cpu-only","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-cpu-single-run-portable-v2","profile_sha256":"49e373f1cbf314e7fab2d176db295f3d3d9ddbbcbd724bbde988ef60ad767dee","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"m49-tgs-portable-review-v2","contract_sha256":"9dd80c8e2504559d2156fca933de6eb27901e35305e6853aeb84707e1cb13892","publication":"observatory","result_kind":"recorded-perception-qualification","result_schema":"missioncore.recorded-tgs-costmap-review/v2","schema_version":"missioncore.observatory-portable-result-contract/v2","version":2},"setup_id":"m49-tgs-portable-v2","source_adapter":{"adapter_id":"xgrids-k1-recorded-observatory-v2","contract_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","version":2},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["point-cloud","trajectory","video"],"seekable":true},"version":3},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"ddrnet-portable-runtime-config-v2","kind":"configuration","sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"component_id":"ddrnet-recorded-profile-v1","kind":"profile","sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"component_id":"ddrnet-recorded-runner-v1","kind":"runner","sha256":"b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"vegetation-mission-policy-v1","kind":"policy","sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"component_id":"vegetation-provider-label-map-v1","kind":"provider-map","sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"definition_id":"ai-segmentation-ddrnet","definition_sha256":"04dd11b9bca4956bc253c970a9020a5fac80e9ef5981ff1fffc32b9646087fec","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"ddrnet_39","artifacts":[{"byte_length":259419077,"role":"checkpoint","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"}],"model_id":"goose-ddrnet-class-512","release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-segmentation-ddrnet-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-ai-layer-v1","contract_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","version":1},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["video"],"seekable":true},"version":1},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"eomt-recorded-dependency-set-v1","kind":"dependency-set","sha256":"4eb1f8d33236806e74f9e5bb96b7dce2ac37623dc39b2184be2aa8d7d00e983e"},{"component_id":"eomt-recorded-orchestrator-v1","kind":"orchestrator","sha256":"d3e9435939444ab35b27a744ac314e289ebd66a13fa56e3d59f121e088d22774"},{"component_id":"eomt-recorded-profile-v1","kind":"profile","sha256":"ea583966bc3409f5cf563cbf4fad05e366907e67187082eb692aff53d9f5d875"},{"component_id":"eomt-recorded-runner-v1","kind":"runner","sha256":"1e64869de48d10f1531c742e6067c4c3ae2a709c5eb0d770d1fab74b4a2431ff"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"}],"definition_id":"ai-segmentation-eomt","definition_sha256":"387f42bdf707b0e3e357fec1cfb5aa90a64133ebf0095f9b01d749ca2364d47c","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"EomtForUniversalSegmentation","artifacts":[{"byte_length":1575,"role":"config-json","sha256":"7f4aa94fa4e43c0dbd79a5420edb511120aef62bd82bfbcbcece79948286a650"},{"byte_length":1276175488,"role":"model-weights","sha256":"c265da9a74f58f5c3f4826d23ca4ca78beac0b106cca5842beca61580de5b782"},{"byte_length":666,"role":"preprocessor-config","sha256":"97e2fbf7f0bdba2cfc90251c5133bae9c27ddc9c4410509f40670be2332854e7"}],"model_id":"tue-mps/cityscapes_semantic_eomt_large_1024","release_id":"eomt-cityscapes-large-1024-v1","revision":"8d6b6d1a3f7b50d441afd7d247c2ed10db186e8f"}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-segmentation-eomt-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-ai-layer-v1","contract_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","version":1},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["video"],"seekable":true},"version":1},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"rf-detr-recorded-profile-v1","kind":"profile","sha256":"4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0"},{"component_id":"rf-detr-recorded-runner-v1","kind":"runner","sha256":"4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0"}],"definition_id":"ai-detection-rf-detr","definition_sha256":"598ce44f087c392ee95a024c3c45c95bdd02ad8530a3ccbac13422c2ad2f4a94","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"RF-DETR-Large-TensorRT","artifacts":[{"byte_length":68316388,"role":"tensorrt-engine","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"}],"model_id":"rf-detr/large-native-kb4","release_id":"rf-detr-large-native-kb4-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-v1","profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-detection-rf-detr-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-ai-layer-v1","contract_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","version":1},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["video"],"seekable":true},"version":1},{"authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"components":[{"component_id":"camera-source-recorded-v1","kind":"orchestrator","sha256":"87c9e8864f9469719e69bfd750c418e077944a6260ffc6fd3ce12daf4a1da7d5"},{"component_id":"k1-camera-1-calibration-v1","kind":"calibration","sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9"},{"component_id":"k1-valid-fov-identity-v1","kind":"valid-fov-identity","sha256":"b4dd8ddf2b87c1d520ee8a0868c4fea062d7c14d1bae73ccabd3abe1f3acbac2"},{"component_id":"k1-valid-fov-mask-v1","kind":"valid-fov-mask","sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"},{"component_id":"m49-tgs-portable-profile-v2","kind":"configuration","sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"component_id":"object-distance-recorded-profile-v1","kind":"profile","sha256":"0e3e426e2f768bc019a3715a50fc77a88626869abd9fa919e1aef5763d0c53da"},{"component_id":"object-distance-recorded-runner-v1","kind":"runner","sha256":"0e3e426e2f768bc019a3715a50fc77a88626869abd9fa919e1aef5763d0c53da"},{"component_id":"rf-detr-recorded-dependency-v1","kind":"dependency-set","sha256":"4eb580eb938164bf0624e94fdc3b046aacf32fb8022c93c67fa26bab7c3d19d0"}],"definition_id":"ai-range-object-distance","definition_sha256":"af5e637b78c670930b60cd4527b611aba4af601e6da58aa4dc8326ea6e13c5c2","executor":{"contour_id":"worker-006","image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","reason":null,"reason_code":null,"release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721","state":"ready"},"models":[{"architecture":"RF-DETR-Large-TensorRT","artifacts":[{"byte_length":68316388,"role":"tensorrt-engine","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"}],"model_id":"rf-detr/large-native-kb4","release_id":"rf-detr-large-native-kb4-v1","revision":null}],"resource_profile":{"accelerator_id":"nvidia-rtx-4090","allowed_checkpoints":[],"checkpoint_policy":"non-checkpointable","concurrency":1,"contour_id":"worker-006","profile_id":"worker006-single-gpu-sequential-ai-object-distance-v1","profile_sha256":"c244efed459915508044fed4ef0e73c810fbe750e5e379d06723f734bd4385ca","schema_version":"missioncore.observatory-portable-resource-profile/v2"},"result_contract":{"contract_id":"ai-layer-result","contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","publication":"observatory","result_kind":"recorded-ai-layer-review","result_schema":"missioncore.recorded-ai-layer-review/v1","schema_version":"missioncore.observatory-portable-result-contract/v2","version":1},"setup_id":"ai-range-object-distance-v1","source_adapter":{"adapter_id":"xgrids-k1-recorded-observatory-v2","contract_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","version":2},"source_requirements":{"archive_id":"xgrids-k1.viewer-live.evidence","calibration_identity_sha256":"05f3ad9b38b3a4fc95388a8ec83da83c745e217709e51787b3d5aad0969f6fa9","calibration_slot":"camera_1","camera_height":600,"camera_semantic_channel_id":"camera.video.recorded","camera_source_id":"sensor.camera.right","camera_width":800,"exactly_one_media_epoch":true,"plugin_id":"nodedc.device.xgrids-lixelkity-k1","recorded_media_init_sha256":"e2279963e16d84c91d68e7dbb1f7efed840533387dfeb844b7398bff45fbde38","recorded_media_type":"video/mp4; codecs=\"avc1.641028\"","required_modalities":["point-cloud","trajectory","video"],"seekable":true},"version":1}],"schema_version":"missioncore.observatory-portable-run-definition-registry/v2"} \ No newline at end of file diff --git a/tests/fixtures/observatory/retired-fixed-lab/observatory-worker-runtime-candidates.json b/tests/fixtures/observatory/retired-fixed-lab/observatory-worker-runtime-candidates.json new file mode 100644 index 00000000..f525ecf4 --- /dev/null +++ b/tests/fixtures/observatory/retired-fixed-lab/observatory-worker-runtime-candidates.json @@ -0,0 +1 @@ +{"candidates":[{"adapter_id":"lab-v1-installed-package-worker006-v1","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"0b6958e3a1b4e12e04619f447ca9ce915021aa1aaa6034ea6bc309c26efbd060","definition_id":"lab-v1-eomt-ddrnet-portable","definition_sha256":"269d71a24b4e63cff54e01273f9d4b35fc6cdd72bc6fadec206169ae0777e6ac","definition_version":2,"executor":{"image_sha256":"5ad7d95baac63af13812cb693d492add4e806a333aba8e60edb2ea1aba754373","release_id":"lab-v1-installed-package-v1","release_sha256":"667858623962cd6d9849a8985b803f59e429916b5c56f76a6fc6c80c0c54526b"},"model_manifest_sha256":"3fd2d43af73bd73f89d9ffae95d8770cfdeb46033ec967509124fac6ae4afe56","phases":[{"phase_id":"source-delivery","state":"implemented"},{"phase_id":"prepare-source","state":"implemented"},{"phase_id":"eomt-step","state":"implemented"},{"phase_id":"ddrnet-step","state":"implemented"},{"phase_id":"assemble-result","state":"implemented"},{"phase_id":"result-publication","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"b3dfaa8e20a0f22fc510d062ac469f010a3281c650059d9ea134f0b3ccb38d9a","reusable_assets":[{"asset_id":"agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"5ad7d95baac63af13812cb693d492add4e806a333aba8e60edb2ea1aba754373"},{"asset_id":"ddrnet-checkpoint","byte_length":259419077,"component_id":null,"kind":"model-artifact","model_artifact_role":"checkpoint","model_release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"},{"asset_id":"ddrnet-goose-mapping","byte_length":1427,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f"},{"asset_id":"ddrnet-goose-runner","byte_length":32877,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1"},{"asset_id":"ddrnet-portable-config","byte_length":4324,"component_id":"ddrnet-portable-runtime-config-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"asset_id":"ddrnet-step-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"e6c986100613ec804f0e0076ca8695abf43ff88ef9d5d85f6857e0b41db74051"},{"asset_id":"eomt-environment","byte_length":211776082,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"eomt-model-cache","byte_length":2552355458,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c"},{"asset_id":"eomt-python-environment","byte_length":5120848705,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20"},{"asset_id":"eomt-runner-bundle","byte_length":145141,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7"},{"asset_id":"eomt-step-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"adba3dc8c97b161ba261ec44fca9ebe1680f117d1bcb1481440172cc3331a174"},{"asset_id":"eomt-transformers-environment","byte_length":225272284,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9"},{"asset_id":"k1-valid-fov-root","byte_length":6019,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e"},{"asset_id":"lab-v1-definition-registry","byte_length":7177,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"1de9a07153fa6f51088aecdbcf74d12c9e58716c5feb0145d6e54f20a8c300cb"},{"asset_id":"lab-v1-package-contract","byte_length":3531,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"c7a576aba09ccb0a343ad46ad90f1dab589ed51353d575026a508f8d6fa8dcc4"},{"asset_id":"vegetation-policy","byte_length":3022,"component_id":"vegetation-mission-policy-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"asset_id":"vegetation-provider-map","byte_length":2756,"component_id":"vegetation-provider-label-map-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"lab-v1-eomt-ddrnet-portable-v1","source_adapter_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","state":"ready"},{"adapter_id":"m49-tgs-worker006-portable-v2","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"65cd2063146a1dd320e30d5f4e21e4bf0aab1ff683e846926cbbfbe25a9f8a5e","definition_id":"m49-tgs-portable","definition_sha256":"f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb","definition_version":3,"executor":{"image_sha256":"f9278ab21aa65045be993dd19bffc25f49955e19598893ac78cc4761ca63ecf3","release_id":"m49-tgs-portable-executor-v1","release_sha256":"c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa"},"model_manifest_sha256":"489a43448f720a9b5c7993dc8279d167b77191a586f0d87b6d38b81cf728e2f1","phases":[{"phase_id":"source-delivery","state":"implemented"},{"phase_id":"camera-lidar-timeline-materializer","state":"implemented"},{"phase_id":"portable-tgs-input-materializer","state":"implemented"},{"phase_id":"portable-tgs-runner","state":"implemented"},{"phase_id":"result-v2-assembler","state":"implemented"},{"phase_id":"observatory-result-publisher","state":"implemented"}],"resource_profile_sha256":"49e373f1cbf314e7fab2d176db295f3d3d9ddbbcbd724bbde988ef60ad767dee","result_contract_sha256":"9dd80c8e2504559d2156fca933de6eb27901e35305e6853aeb84707e1cb13892","reusable_assets":[{"asset_id":"m49-portable-compiled-runner","byte_length":274168,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"7be449392ef161fb8713b4c984705d2373bc3cd05645332d92b88a8bff0c7db3"},{"asset_id":"m49-portable-compiled-runner-build-seal","byte_length":1014,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"e3bb2e91c70712eff74e8e69718075a407e042fb494616d65984500da42b21a9"},{"asset_id":"m49-portable-executor-release","byte_length":1693,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"c5b0670d943fe0452ef4bbfbc144ab2439a1a674f9ef164798ad9f8b1ecc29fa"},{"asset_id":"m49-portable-profile","byte_length":1683,"component_id":"m49-tgs-portable-profile-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"asset_id":"m49-portable-worker-installation-receipt","byte_length":2672,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"b560ff9e02746cbb760502f2a3b4b7bd564f95ab52d1149d189927a326b1645a"},{"asset_id":"travel-tgs-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7b412020f4d8392d1d1ed1b33beadc44140f0ea8f781e62dd69796042334300f"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"m49-tgs-portable-v2","source_adapter_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-ddrnet","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"66dd1b086b03799b08adde8c64461c7b8e09b183bb9e14f169933e625dcbc070","definition_id":"ai-segmentation-ddrnet","definition_sha256":"04dd11b9bca4956bc253c970a9020a5fac80e9ef5981ff1fffc32b9646087fec","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"c9144b30d054e3d495961486a4aed70ae5f60bcadadb4e3309865ced4123739e","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"ddrnet-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-ddrnet-profile","byte_length":4324,"component_id":"ddrnet-portable-runtime-config-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"c0ff657dadc86607d77d232e84d041fbf2d8b63e86d02319e9cd607220d00f21"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"ddrnet-checkpoint","byte_length":259419077,"component_id":null,"kind":"model-artifact","model_artifact_role":"checkpoint","model_release_id":"lab-v1-ddrnet-39-goose-fine-64-v1","sha256":"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6"},{"asset_id":"ddrnet-goose-mapping","byte_length":1427,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f"},{"asset_id":"ddrnet-goose-runner","byte_length":32877,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1"},{"asset_id":"ddrnet-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"a3b7d22f5d3bfdf2d84444b936c8b01abf8243be652387d7e2024ba7bda587f5"},{"asset_id":"ddrnet-package-contract","byte_length":2307,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"34768724991372beee8a3e21baca66e5467671c2639ec699a55eecf2dc8268b9"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"vegetation-policy","byte_length":3022,"component_id":"vegetation-mission-policy-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"b75c4ac841d7b4bcc57f7a9c8417ca2317d8ecfa499e72a9af8a8591a2ec0d35"},{"asset_id":"vegetation-provider-map","byte_length":2756,"component_id":"vegetation-provider-label-map-v1","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"f2b69046b6a740fd9532d2d88e7fabae7c20fb662f783c9502adc9026406f352"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-segmentation-ddrnet-v1","source_adapter_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-eomt","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"b6c7d84a051bd9c5a163f74cb78bd6aa7a96b6c34e3f5cdfc2f99d4aeca8df7b","definition_id":"ai-segmentation-eomt","definition_sha256":"387f42bdf707b0e3e357fec1cfb5aa90a64133ebf0095f9b01d749ca2364d47c","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"94dc40430c2ac23d45aaf14dd26f85f2ca9ba0ec975fe4b08e585c32dd79a223","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"eomt-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"eomt-environment","byte_length":211776082,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"8c8f343a5368ff17edbb58defa1669f6eccfba767aab897a23693872070ab9e0"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"eomt-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"211852dfae4ab1acbd1195d4968a385ea56bd7bd3d0c4241a6be7e02794999b7"},{"asset_id":"eomt-model-cache","byte_length":2552355458,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"064870e58814b97027d6a7ccd553bf51f5b8e6a8ad82a1cc703584d2dca5690c"},{"asset_id":"eomt-package-contract","byte_length":2649,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"3863c4a3f8328221acf66e70dd0cb66c71b0c93b25ef050c072ba351f3edfa5d"},{"asset_id":"eomt-python-environment","byte_length":5120848705,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"b3f4efc53af491f174b1cff74b3ba03016e67c9c5c74257b49c6e7dd7d853f20"},{"asset_id":"eomt-runner-bundle","byte_length":145141,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"0d08f0492d5ad62903874ea224c505e54a6f6059c8283f586bc79e42d55156b7"},{"asset_id":"eomt-transformers-environment","byte_length":225272284,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f365de01426a33be51a310923c743655634d0868941bbf3f1aae1647fdeadfc9"},{"asset_id":"k1-valid-fov-root","byte_length":6019,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"f4fc2053e4e6213bb364c8773979b755d5682a81b3946c25ff86274bc5f0031e"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-segmentation-eomt-v1","source_adapter_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-rf-detr","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"aae136d27d4c013dec111d2b83c22f55df8dcd0dd73a2be5ed47b67f490164f4","definition_id":"ai-detection-rf-detr","definition_sha256":"598ce44f087c392ee95a024c3c45c95bdd02ad8530a3ccbac13422c2ad2f4a94","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"edef8446597b801f67538e9e1f056cbb55e56bf61ca4127efd97ce98e7473788","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"rf-detr-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"7468138cad115210eda18e7a3350e3423d3d39ac0aae650b3266cdc2bc63fd5d","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"rf-detr-engine","byte_length":68316388,"component_id":null,"kind":"model-artifact","model_artifact_role":"tensorrt-engine","model_release_id":"rf-detr-large-native-kb4-v1","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"},{"asset_id":"rf-detr-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"57e5e9bc3033f3dfa696a9135928b8260702a77aadfcaee97a2eb9ccd28d7b48"},{"asset_id":"rf-detr-package-contract","byte_length":1702,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"00291bebb09af4d615b7670f0f4e5084cd5665d46238a6bb5ff93a76ff95cc18"},{"asset_id":"rf-detr-valid-fov","byte_length":3668,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-detection-rf-detr-v1","source_adapter_sha256":"2b8e624b2b16b00c9dd75b96e4c56c5438aa6889b0b2fa7a2b2da39d6aa81c6e","state":"ready"},{"adapter_id":"ai-modular-package-worker006-v1-object-distance","authority":{"actuation_allowed":false,"commands_enabled":false,"navigation_or_safety_accepted":false,"production_accepted":false},"blockers":[],"candidate_sha256":"ec35befdde1a23fb62eda0de582420cd858c9cc7ad46a82f1cf05f07ce2fe39e","definition_id":"ai-range-object-distance","definition_sha256":"af5e637b78c670930b60cd4527b611aba4af601e6da58aa4dc8326ea6e13c5c2","definition_version":1,"executor":{"image_sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab","release_id":"ai-modular-installed-package-v1","release_sha256":"97bfe743689766285b22627c4020d10df7949ef1f4546ef904dccb9ca4c6f721"},"model_manifest_sha256":"edef8446597b801f67538e9e1f056cbb55e56bf61ca4127efd97ce98e7473788","phases":[{"phase_id":"source-materialization","state":"implemented"},{"phase_id":"camera-source","state":"implemented"},{"phase_id":"object-distance-inference","state":"implemented"},{"phase_id":"result-assembly","state":"implemented"}],"resource_profile_sha256":"c244efed459915508044fed4ef0e73c810fbe750e5e379d06723f734bd4385ca","result_contract_sha256":"2316c027ed6014d3ca5632e38de3bbed448ca79e7243fb300510565b21d56305","reusable_assets":[{"asset_id":"ai-module-agent-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"7a1d425b4678dcade7d7d6ffd14733d639a4df29f45e1759ba4c512e930da8ab"},{"asset_id":"ai-module-definition-registry","byte_length":21610,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"bb62449f5178cd8326409875987f2f0a6502fd1ef53ff928e5a523488c8d7b30"},{"asset_id":"ai-module-m49-profile","byte_length":1683,"component_id":"m49-tgs-portable-profile-v2","kind":"definition-component","model_artifact_role":null,"model_release_id":null,"sha256":"6128d6af7e6137f9a9473db045e3b155e2105319159f17c32f344b4aedf823a9"},{"asset_id":"camera-source-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"af42a26fc646483a1c34c1a2760c54ceea7b15792927aa69f4793f4694ee5561"},{"asset_id":"eomt-ffmpeg-runtime","byte_length":256208352,"component_id":null,"kind":"local-tree","model_artifact_role":null,"model_release_id":null,"sha256":"03651449fdcccec847a0f1241e1663a82cf374bd94e7470b4ddb0c0e46d88c69"},{"asset_id":"k1-camera-lidar-calibration","byte_length":72996000,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"0685d24219d8236caf8b7f1685e93f6d6b59e7fd015a768d88a92bbe8b154944"},{"asset_id":"object-distance-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"03908003f7531f677fae50ffad12019c6a62ada773f7e84431bfb9c35982c081"},{"asset_id":"object-distance-package-contract","byte_length":2096,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"7e019064c94884f670d2babecdbd69c6d45082d709ef4cdc6421e3498d1c2c69"},{"asset_id":"rf-detr-engine","byte_length":68316388,"component_id":null,"kind":"model-artifact","model_artifact_role":"tensorrt-engine","model_release_id":"rf-detr-large-native-kb4-v1","sha256":"b8a40b3580edff001ec9680de68707242294ff590ab296000fae371f1083f695"},{"asset_id":"rf-detr-image","byte_length":null,"component_id":null,"kind":"container-image","model_artifact_role":null,"model_release_id":null,"sha256":"57e5e9bc3033f3dfa696a9135928b8260702a77aadfcaee97a2eb9ccd28d7b48"},{"asset_id":"rf-detr-valid-fov","byte_length":3668,"component_id":null,"kind":"local-file","model_artifact_role":null,"model_release_id":null,"sha256":"a40cee06b7c6f69b6a09a11563dcfd237f3de833b1ccd31459e66692e528ba63"}],"schema_version":"missioncore.observatory-portable-worker-runtime-candidate/v1","setup_id":"ai-range-object-distance-v1","source_adapter_sha256":"4e12be6d2503e2e237eddb290b28d6a7d16cf983855b6d8e6b4e3b65d2feb0de","state":"ready"}],"schema_version":"missioncore.observatory-portable-worker-runtime-registry/v1"} \ No newline at end of file diff --git a/tests/test_camera_frame.py b/tests/test_camera_frame.py index 502e0d95..1a3ab141 100644 --- a/tests/test_camera_frame.py +++ b/tests/test_camera_frame.py @@ -312,9 +312,7 @@ def test_camera_playback_source_reuses_manifest_and_exposes_exact_segment_clock( assert first == second assert first.segment_count == 3 - assert first.segment_sha256s == tuple( - segment.sha256 for segment in manifest.epochs[0].segments - ) + assert first.segment_sha256s == tuple(segment.sha256 for segment in manifest.epochs[0].segments) assert first.segment_start_times_ns == (0, 1_000_000_000, 2_000_000_000) assert store.prepare_calls == 1 assert inspector.inspect_calls == 1 @@ -325,3 +323,32 @@ def test_camera_frame_rejects_unbounded_memory_cache_configuration(tmp_path: Pat inspector = _Inspector(_manifest(tmp_path)) with pytest.raises(SessionIntegrityError, match="cache bounds"): _service(tmp_path, store, inspector, max_decode_lanes=0) + + +def test_worker_manifest_provider_needs_no_operator_store(tmp_path, monkeypatch): + manifest = _manifest(tmp_path) + inspector = _Inspector(manifest) + calls = [] + + def provider(session, source): + calls.append((session, source)) + return manifest + + service = RecordedCameraFrameService( + None, + inspector, + ffmpeg_path=Path(sys.executable), + cache_root=tmp_path / "cache", + manifest_provider=provider, + ) + monkeypatch.setattr(service, "_decode", lambda m, e, seq: _frame(e, seq)) + assert ( + service.extract("recorded-session", 0).source_fragment_sha256 + == manifest.epochs[0].segments[0].sha256 + ) + assert ( + service.extract("recorded-session", 1).source_fragment_sha256 + == manifest.epochs[0].segments[1].sha256 + ) + assert calls == [("recorded-session", "sensor.camera.right")] + assert inspector.inspect_calls == 0 diff --git a/tests/test_fixed_lab_retirement.py b/tests/test_fixed_lab_retirement.py new file mode 100644 index 00000000..a8dd6d67 --- /dev/null +++ b/tests/test_fixed_lab_retirement.py @@ -0,0 +1,80 @@ +"""Current admission and build must not depend on the retired combined LAB.""" + +import json +import runpy +from pathlib import Path + +import pytest + +from k1link.observatory.portable_run_definitions import PortableRunDefinitionRegistry + +ROOT = Path(__file__).resolve().parents[1] + + +def test_current_registry_preserves_both_models_without_fixed_lab(): + doc = json.loads((ROOT / "config/observatory-portable-run-definitions.json").read_text()) + defs = {d["setup_id"]: d for d in doc["definitions"]} + assert "lab-v1-eomt-ddrnet-portable-v1" not in defs + old = json.loads( + ( + ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" + ).read_text() + )["definitions"][0] + models = { + m["release_id"]: m + for key in ("ai-segmentation-ddrnet-v1", "ai-segmentation-eomt-v1") + for m in defs[key]["models"] + } + assert all(models[m["release_id"]] == m for m in old["models"]) + registry = PortableRunDefinitionRegistry.from_file( + ROOT / "config/observatory-portable-run-definitions.json" + ) + assert len(registry.ready_recorded_definitions()) == 5 + + +def test_old_promotion_cli_cannot_reinstall_fixed_lab(): + with pytest.raises(SystemExit, match="retired"): + runpy.run_path( + str( + ROOT + / "experiments/perception/worker/observatory_portable" + / "promote_installed_lab_v1_package.py" + ), + run_name="__main__", + ) + + +def test_modular_builder_no_longer_executes_legacy_promotion(monkeypatch): + original = runpy.run_path + + def checked(path, *a, **kw): + assert "promote_installed_lab_v1" not in str(path) + return original(path, *a, **kw) + + monkeypatch.setattr(runpy, "run_path", checked) + module = runpy.run_path(str(ROOT / "scripts/build_modular_ai_worker_release.py")) + assert module["_DDRNET_ASSETS"][0][0] == "ddrnet-checkpoint" + + +def test_build_current_modular_release_without_fixed_definition(tmp_path): + module = runpy.run_path(str(ROOT / "scripts/build_modular_ai_worker_release.py")) + output = tmp_path / "release" + module["build"]( + output=output, + agent_image="1" * 64, + camera_image="2" * 64, + ddrnet_image="3" * 64, + eomt_image="4" * 64, + rf_detr_image="5" * 64, + object_distance_image="6" * 64, + source_tree_sha="7" * 64, + engine_release_root=r"D:\runtime\release", + engine_work_root=r"D:\runtime\work", + ) + registry = PortableRunDefinitionRegistry.from_file( + output / "observatory-portable-run-definitions.json" + ) + assert len(registry.ready_recorded_definitions()) == 5 + assert all(d.setup_id != "lab-v1-eomt-ddrnet-portable-v1" for d in registry.definitions) diff --git a/tests/test_lab_data_deletion.py b/tests/test_lab_data_deletion.py new file mode 100644 index 00000000..60515a17 --- /dev/null +++ b/tests/test_lab_data_deletion.py @@ -0,0 +1,183 @@ +from pathlib import Path +from types import SimpleNamespace + +import httpx +import pytest + +from k1link.laboratory.data_deletion import LabDeletionError, OwnedLabData +from k1link.laboratory.deletion_coordinator import LabDeletionCoordinator +from k1link.laboratory.local_presentations import LocalPresentations + + +def owned(tmp_path): + root = tmp_path / "files" + root.mkdir() + return OwnedLabData(tmp_path / "state", {"data": root}), root + + +def test_delete_shared_files_last_owner_and_repeat(tmp_path): + store, root = owned(tmp_path) + (root / "shared").write_bytes(b"common") + (root / "private").write_bytes(b"result") + shared = {"root": "data", "path": "shared"} + store.register("a", [shared, {"root": "data", "path": "private"}], complete=True) + store.register("b", [shared], complete=True) + assert store.delete(["a"])["state"] == "deleted" + assert not (root / "private").exists() and (root / "shared").exists() + assert store.delete(["a"])["state"] == "deleted" + store.delete(["b"]) + assert not (root / "shared").exists() + with pytest.raises(LabDeletionError): + store.register("a", [], complete=True) + + +def test_unknown_link_and_partial_inventory_refuse_without_deleting(tmp_path): + store, root = owned(tmp_path) + source = tmp_path / "original" + source.write_bytes(b"source") + (root / "link").symlink_to(source) + with pytest.raises(LabDeletionError): + store.register("a", [{"root": "data", "path": "link"}], complete=True) + for member in ("../original", "/original", "", "a/../../original"): + with pytest.raises(LabDeletionError): + store.register("a", [{"root": "data", "path": member}], complete=True) + with pytest.raises(LabDeletionError): + store.register("a", [], complete=False) + with pytest.raises(LabDeletionError): + store.delete(["unknown"]) + assert source.read_bytes() == b"source" + + +def test_interrupted_delete_retries_remaining_files(tmp_path, monkeypatch): + store, root = owned(tmp_path) + for name in ("one", "two"): + (root / name).write_bytes(b"owned") + store.register("a", [{"root": "data", "path": x} for x in ("one", "two")], + complete=True) + unlink = Path.unlink + def fail(path, *args, **kwargs): + if path.name == "two": + raise OSError("device temporarily unavailable") + return unlink(path, *args, **kwargs) + with monkeypatch.context() as context: + context.setattr(Path, "unlink", fail) + with pytest.raises(OSError): + store.delete(["a"]) + assert not (root / "one").exists() and (root / "two").exists() + assert store.delete(["a"])["state"] == "deleted" + assert not (root / "two").exists() + + +def test_worker_failure_keeps_history_and_local_data_until_retry(tmp_path, monkeypatch): + key = "observatory-run-" + "a" * 32 + hidden = [] + queue = SimpleNamespace(get=lambda _: SimpleNamespace(state="failed", result_id=None), + hide_deleted_projection=hidden.append) + coordinator = LabDeletionCoordinator( + store=SimpleNamespace(data_dir=tmp_path), queue=queue, compositions=None, + copies=LocalPresentations(tmp_path), + gateway=SimpleNamespace(base_url="http://worker", token=lambda: "private")) + file = tmp_path / "private-output" + file.write_bytes(b"owned") + coordinator.local.register(key, [{"root": "core", "path": file.name}], complete=True) + monkeypatch.setattr("k1link.laboratory.deletion_coordinator.inventory_local", + lambda *args: None) + status = [503] + def respond(request): + if status[0] == 503: + return httpx.Response(503) + return httpx.Response(200, json={"state": "deleted", "owners": [key]}) + original = httpx.Client + monkeypatch.setattr(httpx, "Client", lambda **kw: + original(**kw, transport=httpx.MockTransport(respond))) + with pytest.raises(LabDeletionError): + coordinator.delete("job", key) + assert file.exists() and not hidden + status[0] = 200 + coordinator.delete("job", key) + assert not file.exists() and hidden == [key] + coordinator.delete("job", key) + assert hidden == [key] + + +def test_waiting_for_worker_does_not_lock_other_lab_status(tmp_path, monkeypatch): + import threading + + key = 'observatory-run-' + 'b' * 32 + copies = LocalPresentations(tmp_path) + hidden = [] + queue = SimpleNamespace(get=lambda _: SimpleNamespace(state='failed', result_id=None), + hide_deleted_projection=hidden.append) + coordinator = LabDeletionCoordinator( + store=SimpleNamespace(data_dir=tmp_path), queue=queue, compositions=None, + copies=copies, gateway=SimpleNamespace(base_url='http://worker', token=lambda: 'private')) + original = httpx.Client + + def respond(request): + observed = [] + thread = threading.Thread(target=lambda: observed.append(copies.snapshot()), daemon=True) + thread.start() + thread.join(1) + assert observed, 'Worker request must not hold the global presentation lock' + with pytest.raises(ValueError, match='удаляется'): + copies.acquire(key) + return httpx.Response(200, json={'state': 'deleted', 'owners': [key]}) + + monkeypatch.setattr(httpx, 'Client', lambda **kw: + original(**kw, transport=httpx.MockTransport(respond))) + coordinator.delete('job', key) + assert hidden == [key] + + +def test_nested_legacy_replays_removed_without_source_or_other_lab(tmp_path): + import json + + from k1link.laboratory.deletion_inventory import inventory_local + + root = tmp_path / "core" + root.mkdir() + cache = root / "integrated-perception-overlays" / "original-session" + selected = "e10-integrated-perception-" + "a" * 64 + retained = "e10-integrated-perception-" + "b" * 64 + for key in (selected, retained): + folder = cache / key + folder.mkdir(parents=True) + (folder / "view.rrd").write_bytes(b"replay") + (folder / "view.rrd.cache.json").write_text(json.dumps({"result_id": key})) + (cache / "admission.json").write_text(json.dumps({"result_id": selected})) + source = root / "recordings" / "original.rrd" + source.parent.mkdir() + source.write_bytes(b"original") + owned = OwnedLabData(tmp_path / "state", {"core": root}) + inventory_local(owned, [selected]) + owned.delete([selected]) + assert not (cache / selected).exists() + assert not (cache / "admission.json").exists() + assert (cache / retained / "view.rrd").read_bytes() == b"replay" + assert source.read_bytes() == b"original" + + +def test_projection_owned_derived_recording_does_not_delete_originals(tmp_path): + import json + + from k1link.laboratory.deletion_inventory import inventory_local + + root = tmp_path / "core" + selected = "m49-tgs-portable-review-" + "c" * 64 + folder = root / "recordings" / selected + folder.mkdir(parents=True) + (folder / "scene.operator-v12.rrd").write_bytes(b"derived") + (folder / "source.raw").write_bytes(b"must survive") + (folder / "scene.operator-v12.rrd.cache.json").write_text(json.dumps({ + "schema_version": "missioncore.derived-rerun-recording-cache/v12", + "session_id": selected, + })) + original = root / "recordings" / "source-session" + original.mkdir() + (original / "scene.operator-v12.rrd").write_bytes(b"source recording") + owned = OwnedLabData(tmp_path / "state", {"core": root}) + inventory_local(owned, [selected]) + owned.delete([selected]) + assert not (folder / "scene.operator-v12.rrd").exists() + assert (folder / "source.raw").read_bytes() == b"must survive" + assert (original / "scene.operator-v12.rrd").read_bytes() == b"source recording" diff --git a/tests/test_laboratory_archive_store.py b/tests/test_laboratory_archive_store.py new file mode 100644 index 00000000..8a3652c2 --- /dev/null +++ b/tests/test_laboratory_archive_store.py @@ -0,0 +1,156 @@ +import json +import shutil +from dataclasses import replace + +import pytest + +from k1link.artifact_gateway import ArtifactIntegrityError, CentralArtifactStore +from k1link.laboratory.archive_store import ( + CATALOG_SCHEMA, + INDEX_SCHEMA, + LaboratoryArchiveStore, +) + + +def archive(tmp_path, member_path=".runtime/compute-experiments/e1/result.bin"): + root = tmp_path / "runtime-a" / "store" + store = CentralArtifactStore(root, create=True) + source = tmp_path / "payload.bin" + source.write_bytes(b"recorded-result\x00\xff" * 64) + member = replace(store.publish_file(source), role="file-0") + index = tmp_path / "index.json" + index.write_text(json.dumps({ + "schema_version": INDEX_SCHEMA, + "files": [{"path": member_path, "role": member.role, + "sha256": member.sha256, "bytes": member.byte_length}], + })) + manifest = store.publish_manifest( + artifact_type="laboratory-evidence-archive", subject_id="e1", + members=[member, replace(store.publish_file(index), role="index")], + ) + return root, manifest.manifest_id, member, source.read_bytes(), member_path + + +def test_restore_survives_runtime_volume_relocation_without_source(tmp_path): + root, identity, member, expected, logical = archive(tmp_path) + moved = tmp_path / "another-host-volume" + shutil.move(root, moved) + (tmp_path / "payload.bin").unlink() + store = LaboratoryArchiveStore(moved) + assert store.verify(identity)["bytes"] == len(expected) + restored = store.restore_file(identity, logical, tmp_path / "restored.bin") + assert restored.read_bytes() == expected + assert restored.stat().st_mode & 0o777 == 0o600 + restored.write_bytes(b"edited working copy") + assert store.verify(identity)["bytes"] == len(expected) + + +def test_corrupt_remote_object_is_never_accepted(tmp_path): + root, identity, member, _, logical = archive(tmp_path) + CentralArtifactStore(root).object_path(member.sha256).write_bytes(b"x" * member.byte_length) + with pytest.raises(ArtifactIntegrityError, match="checksum"): + LaboratoryArchiveStore(root).restore_file(identity, logical, tmp_path / "restored.bin") + assert not (tmp_path / "restored.bin").exists() + + +@pytest.mark.parametrize( + "logical", ["../escape", "/absolute", "C:/host", "a/../b", "C:relative", "\\server\\share"] +) +def test_archive_cannot_smuggle_host_paths(tmp_path, logical): + root, identity, _, _, _ = archive(tmp_path, logical) + with pytest.raises(ArtifactIntegrityError): + LaboratoryArchiveStore(root).entries(identity) + + +def test_restore_never_replaces_existing_work(tmp_path): + root, identity, _, _, logical = archive(tmp_path) + target = tmp_path / "existing.bin" + target.write_bytes(b"unsaved user work") + with pytest.raises(ArtifactIntegrityError, match="already exists"): + LaboratoryArchiveStore(root).restore_file(identity, logical, target) + assert target.read_bytes() == b"unsaved user work" + + +def test_legacy_windows_name_is_only_an_opaque_source_identity(tmp_path): + logical = r".runtime/legacy/C:\old-worker\evidence/result.json" + root, identity, _, expected, _ = archive(tmp_path, logical) + (root / "catalog.json").write_text(json.dumps({ + "schema_version": CATALOG_SCHEMA, + "groups": [{"source_group": ".runtime/legacy", "manifest_id": identity}], + })) + store = LaboratoryArchiveStore(root) + assert store.find_file(logical) == identity + target = tmp_path / "restored.json" + assert store.restore_file(identity, logical, target).read_bytes() == expected + assert not (tmp_path / ".runtime").exists() + + +def test_catalog_resolves_original_path_after_volume_relocation(tmp_path): + root, identity, _, _, logical = archive(tmp_path) + (root / "catalog.json").write_text(json.dumps({ + "schema_version": CATALOG_SCHEMA, + "groups": [{"source_group": ".runtime/compute-experiments/e1", + "manifest_id": identity}], + })) + moved = tmp_path / "moved-store" + shutil.move(root, moved) + assert LaboratoryArchiveStore(moved).find_file(logical) == identity + with pytest.raises(ArtifactIntegrityError, match="absent"): + LaboratoryArchiveStore(moved).find_file(".runtime/compute-experiments/e2/missing.bin") + + +def test_restore_open_race_keeps_other_writers_file(tmp_path, monkeypatch): + root, identity, _, _, logical = archive(tmp_path) + target = tmp_path / "concurrently-created.bin" + original_open = type(target).open + + def raced_open(path, mode="r", *args, **kwargs): + if path == target and mode == "xb": + with original_open(path, "wb") as stream: + stream.write(b"other writer") + return original_open(path, mode, *args, **kwargs) + + monkeypatch.setattr(type(target), "open", raced_open) + with pytest.raises(FileExistsError): + LaboratoryArchiveStore(root).restore_file(identity, logical, target) + assert target.read_bytes() == b"other writer" + + +def test_explicit_lab_delete_retires_restore_without_destroying_shared_source(tmp_path): + from k1link.laboratory.data_deletion import OwnedLabData + from k1link.laboratory.deletion_inventory import inventory_worker + + result_id = 'e10-integrated-perception-' + 'a' * 64 + logical = f'.runtime/compute-experiments/e10/worker-results/{result_id}/frame.bin' + root, deleted_manifest, member, expected, _ = archive(tmp_path, logical) + _, kept_manifest, _, _, kept_path = archive(tmp_path, '.runtime/recorded/source.bin') + (root / 'catalog.json').write_text(json.dumps({ + 'schema_version': CATALOG_SCHEMA, + 'groups': [ + {'source_group': '.runtime/compute-experiments/e10', + 'manifest_id': deleted_manifest}, + {'source_group': '.runtime/recorded', 'manifest_id': kept_manifest}, + ], + })) + roots = {'archive': root} + for name in ('lab', 'ai', 'tgs'): + roots[name] = tmp_path / name + roots[name].mkdir() + result = roots['lab'] / '.runtime/compute-experiments/e10/worker-results' / result_id + result.mkdir(parents=True) + (result / 'result.json').write_text(json.dumps({'result_id': result_id})) + (result / 'frame.bin').write_bytes(expected) + owned = OwnedLabData(tmp_path / 'ownership', roots) + inventory_worker(owned, [result_id]) + receipt = owned.delete([result_id]) + assert receipt['state'] == 'deleted' + assert not result.exists() + assert CentralArtifactStore(root).object_path(member.sha256).read_bytes() == expected + retained = LaboratoryArchiveStore(root) + assert retained.entries(deleted_manifest) == [] + with pytest.raises(ArtifactIntegrityError, match='not uniquely'): + retained.restore_file(deleted_manifest, logical, tmp_path / 'resurrected.bin') + restored = retained.restore_file(kept_manifest, kept_path, tmp_path / 'source.bin') + assert restored.read_bytes() == expected + inventory_worker(owned, [result_id]) + assert owned.delete([result_id])['state'] == 'deleted' diff --git a/tests/test_laboratory_execution.py b/tests/test_laboratory_execution.py index 9d5d8301..89f607e5 100644 --- a/tests/test_laboratory_execution.py +++ b/tests/test_laboratory_execution.py @@ -18,6 +18,7 @@ from k1link.laboratory import ( LaboratoryRunner, LaboratoryRunRequest, ) +from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority REPOSITORY_ROOT = Path(__file__).resolve().parents[1] @@ -140,9 +141,7 @@ def test_repository_registry_classifies_every_evidence_definition() -> None: "lab-v1-vegetation-shadow", } ) - assert len(execution.definitions) + len(execution.legacy_work_ids) == len( - evidence.definitions - ) + assert len(execution.definitions) + len(execution.legacy_work_ids) == len(evidence.definitions) def test_legacy_is_read_only_and_experimental_requires_bounded_adapter() -> None: @@ -178,6 +177,7 @@ def test_runner_uses_common_telemetry_evidence_and_immutable_receipt( telemetry_path = tmp_path / "pipeline.jsonl" runner = LaboratoryRunner( + worker_authority=WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0), registry=execution, evidence_registry=evidence, sink=JsonlPipelineTelemetrySink(telemetry_path), @@ -218,6 +218,7 @@ def test_runner_rejects_undeclared_input_before_adapter(tmp_path: Path) -> None: raise AssertionError("must not run") runner = LaboratoryRunner( + worker_authority=WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0), registry=execution, evidence_registry=evidence, sink=JsonlPipelineTelemetrySink(tmp_path / "pipeline.jsonl"), @@ -259,6 +260,7 @@ def test_m48_evaluation_uses_registered_adapter_and_common_receipt( score, ) runner = LaboratoryRunner( + worker_authority=WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0), registry=execution, evidence_registry=evidence, sink=JsonlPipelineTelemetrySink(tmp_path / "pipeline.jsonl"), @@ -295,3 +297,22 @@ def _canonical_json(value: object) -> bytes: separators=(",", ":"), ensure_ascii=False, ).encode("utf-8") + + +def test_operator_run_rejected_before_adapter_or_disk_write(tmp_path, monkeypatch): + monkeypatch.delenv("MISSIONCORE_LAB_RUNTIME_ROLE", raising=False) + evidence, execution = _registries() + request = _request(tmp_path) + calls = [] + runner = LaboratoryRunner( + registry=execution, + evidence_registry=evidence, + sink=JsonlPipelineTelemetrySink(tmp_path / "telemetry.jsonl"), + adapters={"e33-worker-shadow": lambda r: calls.append(r)}, + ) + with pytest.raises(LaboratoryExecutionError, match="operator execution is disabled"): + runner.run(request) + assert calls == [] + assert not request.output_root.exists() + assert not request.receipt_root.exists() + assert not (tmp_path / "telemetry.jsonl").exists() diff --git a/tests/test_laboratory_worker_gateway.py b/tests/test_laboratory_worker_gateway.py new file mode 100644 index 00000000..70505f11 --- /dev/null +++ b/tests/test_laboratory_worker_gateway.py @@ -0,0 +1,139 @@ +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from k1link.laboratory.execution_authority import ( + LaboratoryPlacementError, + WorkerLaboratoryAuthority, +) +from k1link.laboratory.worker_gateway import ( + LaboratoryGatewayConfiguration, + LaboratoryWorkerGateway, + build_laboratory_worker_gateway_router, +) + + +def client(gateway): + app = FastAPI() + app.include_router(build_laboratory_worker_gateway_router(gateway)) + return TestClient(app) + + +def configured(tmp_path, handler): + token = tmp_path / "token" + token.write_text("a" * 48) + token.chmod(0o600) + return LaboratoryWorkerGateway( + LaboratoryGatewayConfiguration("http://127.0.0.1:19087", token), + transport=httpx.MockTransport(handler), + ) + + +def test_no_local_fallback(tmp_path): + with client(LaboratoryWorkerGateway(None)) as c: + assert c.get("/api/v1/laboratory/e29/catalog").status_code == 503 + assert list(tmp_path.iterdir()) == [] + + +def test_range_and_query_stream_without_staging(tmp_path): + def upstream(r): + assert r.headers["authorization"] == "Bearer " + "a" * 48 + assert r.headers["accept-encoding"] == "identity" + assert r.headers["range"] == "bytes=1-3" + assert str(r.url) == "http://127.0.0.1:19087/api/v1/laboratory/e29/video?quality=x" + return httpx.Response( + 206, + content=b"abc", + headers={ + "content-range": "bytes 1-3/10", + "etag": '"sealed"', + "set-cookie": "secret=ignored", + }, + ) + + with client(configured(tmp_path, upstream)) as c: + r = c.get("/api/v1/laboratory/e29/video?quality=x", headers={"range": "bytes=1-3"}) + assert r.status_code == 206 and r.content == b"abc" + assert r.headers["content-range"] == "bytes 1-3/10" + assert r.headers["etag"] == '"sealed"' + assert "set-cookie" not in r.headers + assert [p.name for p in tmp_path.iterdir()] == ["token"] + + +def test_mutation_not_retried_and_redirect_rejected(tmp_path): + calls = [] + + def upstream(r): + calls.append(r.content) + return httpx.Response(307, headers={"location": "https://elsewhere.test"}) + + with client(configured(tmp_path, upstream)) as c: + assert c.post("/api/v1/laboratory/evaluate", json={"a": 1}).status_code == 503 + assert len(calls) == 1 + + +def test_response_budget_and_capacity_release(tmp_path, monkeypatch): + monkeypatch.setattr("k1link.laboratory.worker_gateway.MAX_RESPONSE_BYTES", 3) + gateway = configured(tmp_path, lambda _: httpx.Response(200, content=b"too big")) + with client(gateway) as c: + for _ in range(10): + assert c.get("/api/v1/laboratory/result").status_code == 503 + assert gateway._capacity._value == 8 + + +def test_request_budget(tmp_path, monkeypatch): + monkeypatch.setattr("k1link.laboratory.worker_gateway.MAX_REQUEST_BYTES", 3) + + def forbidden(_): + raise AssertionError("oversized request reached Worker") + + with client(configured(tmp_path, forbidden)) as c: + assert c.post("/api/v1/laboratory/result", content=b"large").status_code == 413 + + +def test_worker_authority_blocks_operator_and_escape(tmp_path, monkeypatch): + monkeypatch.delenv("MISSIONCORE_LAB_RUNTIME_ROLE", raising=False) + assert WorkerLaboratoryAuthority.from_environment() is None + authority = WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0) + authority.admit_outputs(tmp_path / "job" / "result") + with pytest.raises(LaboratoryPlacementError): + authority.admit_outputs(tmp_path.parent / "escaped") + (tmp_path / "link").symlink_to(tmp_path.parent, target_is_directory=True) + with pytest.raises(LaboratoryPlacementError): + authority.admit_outputs(tmp_path / "link" / "escaped") + + +def test_http_remote_disallowed(tmp_path): + with pytest.raises(ValueError): + LaboratoryGatewayConfiguration("http://example.test", tmp_path / "token") + + +def test_replay_format_capabilities_and_encoded_points(tmp_path): + import gzip + + payload = b"recorded-point-data" * 100 + encoded = gzip.compress(payload) + + def upstream(r): + assert r.headers["x-m48-review-capability"] == "review-token" + return httpx.Response( + 200, + stream=httpx.ByteStream(encoded), + headers={ + "content-encoding": "gzip", + "content-length": str(len(encoded)), + "x-rerun-format": "RRF2", + "x-uncompressed-content-length": str(len(payload)), + }, + ) + + with client(configured(tmp_path, upstream)) as c: + response = c.get( + "/api/v1/laboratory/recorded-points", + headers={"x-m48-review-capability": "review-token"}, + ) + assert response.content == payload + assert response.headers["content-length"] == str(len(encoded)) + assert response.headers["x-rerun-format"] == "RRF2" + assert response.headers["x-uncompressed-content-length"] == str(len(payload)) diff --git a/tests/test_laboratory_worker_sources.py b/tests/test_laboratory_worker_sources.py new file mode 100644 index 00000000..8da430e9 --- /dev/null +++ b/tests/test_laboratory_worker_sources.py @@ -0,0 +1,50 @@ +import hashlib + +import pytest + +from k1link.laboratory.worker_recorded_sources import WorkerRecordedSources +from k1link.sessions.models import SessionIntegrityError + + +def test_binding_rejects_changed_descriptor_and_source_escape(tmp_path): + directory = tmp_path / "descriptors" + directory.mkdir() + descriptor = directory / "source.json" + payload = b'{"session_id":"test"}' + descriptor.write_bytes(payload) + bindings = { + "schema_version": "missioncore.laboratory-recorded-source-bindings/v1", + "sources": [ + { + "session_id": "test", + "source_name": "camera", + "descriptor": "descriptors/source.json", + "descriptor_sha256": hashlib.sha256(payload).hexdigest(), + "media_root": "media", + } + ], + } + source = WorkerRecordedSources(tmp_path, bindings_document=bindings) + descriptor.write_bytes(b"changed") + with pytest.raises(SessionIntegrityError, match="descriptor changed"): + source.manifest("test", "camera") + descriptor.unlink() + outside = tmp_path.parent / "outside-descriptor" + outside.write_bytes(payload) + descriptor.symlink_to(outside) + with pytest.raises(SessionIntegrityError, match="Invalid Worker camera descriptor"): + source.manifest("test", "camera") + assert not (tmp_path / "bindings.json").exists() + + +def test_source_binding_rejects_ambiguous_or_missing_source(tmp_path): + bindings = { + "schema_version": "missioncore.laboratory-recorded-source-bindings/v1", + "sources": [{"session_id": "test", "source_name": "camera"}], + } + source = WorkerRecordedSources(tmp_path, bindings_document=bindings) + with pytest.raises(SessionIntegrityError, match="not installed"): + source.manifest("other", "camera") + bindings["sources"].append(bindings["sources"][0]) + with pytest.raises(SessionIntegrityError, match="Ambiguous"): + WorkerRecordedSources(tmp_path, bindings_document=bindings) diff --git a/tests/test_local_presentations.py b/tests/test_local_presentations.py new file mode 100644 index 00000000..3c116915 --- /dev/null +++ b/tests/test_local_presentations.py @@ -0,0 +1,117 @@ +import hashlib +import json +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from k1link.laboratory.local_presentations import LocalPresentationError, LocalPresentations +from k1link.web.local_storage_api import build_local_storage_router + + +def fixture(tmp_path): + now = [1000.0] + store = LocalPresentations(tmp_path, clock=lambda: now[0]) + store.root.mkdir() + path = store.root / ("a" * 64 + ".replay.rrd") + path.write_bytes(b"RRF2-complete-video-and-spatial-recording") + artifact = SimpleNamespace( + path=path, + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + byte_length=path.stat().st_size, + ) + sidecar = store.root / ("b" * 64 + ".json") + sidecar.write_text(json.dumps({"sha256": artifact.sha256})) + store.register("run", artifact, sidecar) + return store, now, artifact, sidecar + + +def test_persistence_unpin_starts_full_retention_and_catalog_survives(tmp_path): + store, now, artifact, sidecar = fixture(tmp_path) + store.policy(7) + store.pin("run", True) + now[0] += 40 * 86400 + store.prune() + assert artifact.path.exists() + reloaded = LocalPresentations(tmp_path, clock=lambda: now[0]) + assert reloaded.snapshot()["entries"]["run"]["pinned"] + reloaded.pin("run", False) + reloaded.prune() + assert artifact.path.exists() + now[0] += 7 * 86400 + reloaded.prune() + assert not artifact.path.exists() and not sidecar.exists() + assert reloaded.snapshot()["entries"]["run"]["local"] is False + + +def test_no_purge_of_unknown_files_and_changed_bytes(tmp_path): + store, now, artifact, _ = fixture(tmp_path) + unknown = store.root / "original-unregistered.rrd" + unknown.write_bytes(b"valuable") + artifact.path.write_bytes(b"changed") + now[0] += 100 * 86400 + store.prune() + assert unknown.read_bytes() == b"valuable" + assert artifact.path.read_bytes() == b"changed" + with pytest.raises(LocalPresentationError): + store.pin("run", True) + + +def test_playback_lease_and_pin_protect_delete_and_ttl(tmp_path): + store, now, artifact, _ = fixture(tmp_path) + with store.use("run"): + with pytest.raises(LocalPresentationError): + store.remove("run") + now[0] += 100 * 86400 + store.prune() + assert artifact.path.exists() + store.pin("run", True) + with pytest.raises(LocalPresentationError): + store.remove("run") + + +def test_symlink_is_preserved_without_traversal(tmp_path): + store, _, artifact, _ = fixture(tmp_path) + victim = tmp_path / "source" + victim.write_bytes(artifact.path.read_bytes()) + artifact.path.unlink() + artifact.path.symlink_to(victim) + with pytest.raises(LocalPresentationError): + store.remove("run") + assert victim.exists() + + +def test_shared_file_is_retained_for_other_result(tmp_path): + store, _, artifact, sidecar = fixture(tmp_path) + store.register("other", artifact, sidecar) + store.pin("other", True) + store.remove("run") + assert artifact.path.exists() + assert store.snapshot()["entries"]["other"]["local"] + + +def test_invalid_policy_and_pin_missing_copy_fail_without_mutation(tmp_path): + store, _, _, _ = fixture(tmp_path) + app = FastAPI() + app.include_router(build_local_storage_router(store)) + with TestClient(app) as client: + root = "/api/v1/storage/laboratory" + for value in (0, 366, "7", True): + assert client.put(root + "/policy", json={"retention_days": value}).status_code == 422 + assert ( + client.put(root + "/policy", json={"retention_days": 7}).json()["retention_days"] == 7 + ) + assert client.put(root + "/copies/missing/pin", json={"pinned": True}).status_code == 409 + assert client.delete(root + "/copies/run").status_code == 200 + assert not client.get(root).json()["entries"]["run"]["local"] + + +def test_explicit_lab_deletion_removes_pin_but_not_active_playback(tmp_path): + store, _, artifact, _ = fixture(tmp_path) + store.pin("run", True) + with store.use("run"), pytest.raises(LocalPresentationError): + store.remove("run", delete_lab=True) + store.remove("run", delete_lab=True) + assert not artifact.path.exists() + assert "run" not in store.snapshot()["entries"] diff --git a/tests/test_modular_observatory_api.py b/tests/test_modular_observatory_api.py index ac08995c..e5701982 100644 --- a/tests/test_modular_observatory_api.py +++ b/tests/test_modular_observatory_api.py @@ -36,7 +36,7 @@ def _client(tmp_path: Path) -> tuple[TestClient, dict]: return TestClient(app), catalog -def test_composition_projection_can_be_renamed_and_removed_through_api( +def test_composition_rename_and_delete_without_storage_service_fails_closed( tmp_path: Path, ) -> None: registry = ModuleRegistry.from_file( @@ -95,8 +95,8 @@ def test_composition_projection_can_be_renamed_and_removed_through_api( assert runs.display_name(run.run_id) == "Контрольный прогон" removed = client.delete(f"/api/v1/observatory/ai-composition-runs/{run.run_id}") - assert removed.status_code == 204 - assert runs.list(source_session_id="source-1", include_hidden=False) == () + assert removed.status_code == 503 + assert runs.list(source_session_id="source-1", include_hidden=False) == (run,) assert runs.get(run.run_id) == run diff --git a/tests/test_observatory_installed_lab_package_runner.py b/tests/test_observatory_installed_lab_package_runner.py index 32d1e205..d4a7f5db 100644 --- a/tests/test_observatory_installed_lab_package_runner.py +++ b/tests/test_observatory_installed_lab_package_runner.py @@ -42,8 +42,16 @@ from k1link.observatory.portable_worker_runtime import ( ) REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -DEFINITIONS_FILE = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" -RUNTIME_FILE = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json" +DEFINITIONS_FILE = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) +RUNTIME_FILE = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-worker-runtime-candidates.json" +) def _package_and_runtime(): diff --git a/tests/test_observatory_installed_lab_packages.py b/tests/test_observatory_installed_lab_packages.py index ea2aeb72..acdf01d8 100644 --- a/tests/test_observatory_installed_lab_packages.py +++ b/tests/test_observatory_installed_lab_packages.py @@ -32,8 +32,16 @@ from k1link.observatory.worker_service import ( ) REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -DEFINITIONS_FILE = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" -RUNTIME_FILE = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json" +DEFINITIONS_FILE = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) +RUNTIME_FILE = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-worker-runtime-candidates.json" +) def _registries() -> tuple[PortableRunDefinitionRegistry, PortableWorkerRuntimeRegistry]: diff --git a/tests/test_observatory_installed_lab_v1_promotion.py b/tests/test_observatory_installed_lab_v1_promotion.py index 237e45ea..e0a5fcca 100644 --- a/tests/test_observatory_installed_lab_v1_promotion.py +++ b/tests/test_observatory_installed_lab_v1_promotion.py @@ -39,16 +39,17 @@ def test_generic_lab_v1_promotion_round_trips_all_three_registries( promotion.generate( source_definitions=( - REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" ), source_runtime=( - REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json" + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-worker-runtime-candidates.json" ), ddrnet_config=( - REPOSITORY_ROOT - / "config" - / "perception" - / "lab-v1-eomt-ddrnet-portable-v2.json" + REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json" ), result_assembler_source=( REPOSITORY_ROOT / "src" / "k1link" / "observatory" / "portable_lab_v1_executor.py" @@ -79,9 +80,7 @@ def test_generic_lab_v1_promotion_round_trips_all_three_registries( definition = definitions.resolve_setup("lab-v1-eomt-ddrnet-portable-v1") candidate = runtime.resolve(definition.setup_id, definition.definition_sha256) package = packages.resolve(definition.setup_id, definition.definition_sha256) - bindings = json.loads( - (output / "observatory-installed-lab-asset-bindings.json").read_text() - ) + bindings = json.loads((output / "observatory-installed-lab-asset-bindings.json").read_text()) assert definition.executor.ready is True assert candidate.ready is True @@ -199,16 +198,17 @@ def _generate( ) -> None: promotion.generate( source_definitions=( - REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" ), source_runtime=( - REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json" + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-worker-runtime-candidates.json" ), ddrnet_config=( - REPOSITORY_ROOT - / "config" - / "perception" - / "lab-v1-eomt-ddrnet-portable-v2.json" + REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json" ), result_assembler_source=( REPOSITORY_ROOT / "src" / "k1link" / "observatory" / "portable_lab_v1_executor.py" diff --git a/tests/test_observatory_m49_worker_entrypoint.py b/tests/test_observatory_m49_worker_entrypoint.py index 8f7116e7..15775aa0 100644 --- a/tests/test_observatory_m49_worker_entrypoint.py +++ b/tests/test_observatory_m49_worker_entrypoint.py @@ -44,7 +44,11 @@ from k1link.observatory.worker_service import ( ) REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -DEFINITIONS_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +DEFINITIONS_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) PROFILE_PATH = REPOSITORY_ROOT / "config" / "perception" / "m49-tgs-portable-v2.json" SOURCE_REVISION = "f" * 40 SOURCE_CANDIDATE_SHA256 = "a" * 64 diff --git a/tests/test_observatory_portable_artifact_transport.py b/tests/test_observatory_portable_artifact_transport.py index 2a619352..f1142105 100644 --- a/tests/test_observatory_portable_artifact_transport.py +++ b/tests/test_observatory_portable_artifact_transport.py @@ -54,7 +54,11 @@ from k1link.sessions.models import ( ) REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +REGISTRY_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) NOW = "2026-08-31T10:00:00.000Z" SOURCE_SESSION_ID = "20260831T095500Z_viewer_live" RESULT_ID = "portable-result-transport-001" @@ -63,9 +67,7 @@ RESULT_ID = "portable-result-transport-001" def _ready_registry(tmp_path: Path) -> PortableRunDefinitionRegistry: registry = PortableRunDefinitionRegistry.from_file(REGISTRY_PATH) base = registry.definitions[0] - document = cast( - dict[str, object], json.loads(REGISTRY_PATH.read_text(encoding="utf-8")) - ) + document = cast(dict[str, object], json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))) rows = cast(list[object], document["definitions"]) selected = copy.deepcopy(cast(dict[str, object], rows[0])) selected["executor"] = { @@ -106,9 +108,7 @@ class _Store: replay: ReplayCommand recorded_media: tuple[RecordedMediaArtifact, ...] - def get_session_with_catalog_snapshot( - self, session_id: str - ) -> tuple[SessionDetail, str]: + def get_session_with_catalog_snapshot(self, session_id: str) -> tuple[SessionDetail, str]: assert session_id == SOURCE_SESSION_ID return self.detail, self.catalog_sha256 @@ -116,9 +116,7 @@ class _Store: assert session_id == SOURCE_SESSION_ID return self.replay - def list_recorded_media( - self, session_id: str - ) -> tuple[RecordedMediaArtifact, ...]: + def list_recorded_media(self, session_id: str) -> tuple[RecordedMediaArtifact, ...]: assert session_id == SOURCE_SESSION_ID return self.recorded_media @@ -336,9 +334,7 @@ def _fixture(tmp_path: Path) -> _Fixture: (documents / f"{capability_sha}.json").write_bytes(capability_payload) queue = ObservatoryRecordedJobQueue( data_dir, - definitions=RecordedRunDefinitionRegistry( - (definition.to_recorded_run_definition(),) - ), + definitions=RecordedRunDefinitionRegistry((definition.to_recorded_run_definition(),)), clock=lambda: NOW, ) job, created = queue.submit( @@ -438,9 +434,7 @@ def test_source_members_are_claim_bound_and_materialized_through_cas( assert cas_path != fixture.raw_path assert cas_path.name == raw.sha256 metadata = next( - member - for member in manifest.members - if member.kind == "spatial-replay-metadata" + member for member in manifest.members if member.kind == "spatial-replay-metadata" ) admitted_metadata, metadata_cas_path = fixture.service.materialize_source_member( job_id=fixture.job.job_id, @@ -644,3 +638,190 @@ def test_result_upload_rejects_wrong_digest_and_never_publishes_partial_member( claimant_id="worker-006", ) assert repeated.members[0].uploaded is False + + +def test_source_transport_space_preserves_original_and_reuses_exact_copy(tmp_path, monkeypatch): + from types import SimpleNamespace + + from k1link.observatory import transfer_space + from k1link.observatory.portable_artifact_transport import _publish_exact_cas_member + + source = tmp_path / "source.bin" + source.write_bytes(b"source-evidence") + root = tmp_path / "transport" + digest = hashlib.sha256(source.read_bytes()).hexdigest() + available = [transfer_space.FREE_RESERVE + 4] + monkeypatch.setattr( + transfer_space.shutil, "disk_usage", lambda _: SimpleNamespace(free=available[0]) + ) + with pytest.raises(transfer_space.TransferCapacityError): + _publish_exact_cas_member( + root, source, expected_sha256=digest, expected_byte_length=source.stat().st_size + ) + assert source.read_bytes() == b"source-evidence" + assert not list(root.rglob(".tmp-*")) + available[0] += 1024 + target = _publish_exact_cas_member( + root, source, expected_sha256=digest, expected_byte_length=source.stat().st_size + ) + available[0] = 0 + assert ( + _publish_exact_cas_member( + root, source, expected_sha256=digest, expected_byte_length=source.stat().st_size + ) + == target + ) + + +def test_source_gc_waits_for_queue_then_archive_rebuilds_identically(tmp_path): + from k1link.observatory.portable_artifact_transport import ( + _ordered_camera_epoch_members, + _publish_camera_epoch_archive, + ) + + fixture = _fixture(tmp_path) + args = dict( + job_id=fixture.job.job_id, + claim_token=fixture.claim_token, + claim_generation=fixture.job.claim_generation, + claimant_id="worker-006", + ) + manifest = fixture.service.source_manifest(**args) + original, path = fixture.service.materialize_camera_epoch_archive(**args) + assert fixture.service.collect_source_copies()["protected"] == 1 + fixture.queue.fail( + fixture.job.job_id, + claim_token=fixture.claim_token, + error_code="test-completed", + message="Synthetic failure closed", + ) + assert fixture.service.collect_source_copies()["retired"] == 1 + assert not path.exists() and fixture.raw_path.exists() + # Historical binding survives retirement and the same admitted inputs regenerate + # precisely the same tar; no deletion of a source or re-admission of old models. + rebuilt, target = _publish_camera_epoch_archive( + fixture.service._source_cas, + job=fixture.job, + members=_ordered_camera_epoch_members(manifest.members), + space=fixture.service._transfer_space, + ) + assert rebuilt == original and target == path and path.is_file() + + +def test_package_shortage_is_retryable_before_manifest_or_body(tmp_path, monkeypatch): + from types import SimpleNamespace + + from fastapi import HTTPException + + from k1link.observatory import transfer_space + from k1link.web.observatory_worker_api import _artifact_call, _raise_artifact_or_queue_error + + fixture = _fixture(tmp_path) + package, payload = _result_package(tmp_path, fixture) + available = [transfer_space.FREE_RESERVE + len(package.canonical_bytes) + 4096] + monkeypatch.setattr( + transfer_space.shutil, "disk_usage", lambda _: SimpleNamespace(free=available[0]) + ) + args = dict( + job_id=fixture.job.job_id, + result_sha256=package.manifest_sha256, + manifest_payload=package.canonical_bytes, + claim_token=fixture.claim_token, + claim_generation=fixture.job.claim_generation, + claimant_id="worker-006", + ) + with pytest.raises(HTTPException) as caught: + _artifact_call(lambda: fixture.service.stage_result_manifest(**args)) + assert caught.value.status_code == 503 and caught.value.headers["Retry-After"] == "30" + assert not list(fixture.service._result_staging.rglob("manifest.json")) + assert fixture.queue.get(fixture.job.job_id).state == "running" + available[0] += len(payload) + 10000 + plan = fixture.service.stage_result_manifest(**args) + assert not plan.complete + with pytest.raises(HTTPException) as caught: + _raise_artifact_or_queue_error(transfer_space.TransferCapacityError("space")) + assert caught.value.status_code == 503 + + +def test_completed_upload_retry_needs_no_new_disk_space(tmp_path, monkeypatch): + from types import SimpleNamespace + + from k1link.observatory import transfer_space + + fixture = _fixture(tmp_path) + package, payload = _result_package(tmp_path, fixture) + args = dict( + job_id=fixture.job.job_id, + result_sha256=package.manifest_sha256, + claim_token=fixture.claim_token, + claim_generation=fixture.job.claim_generation, + claimant_id="worker-006", + ) + plan = fixture.service.stage_result_manifest(**args, manifest_payload=package.canonical_bytes) + + async def chunks(): + yield payload + + asyncio.run( + fixture.service.upload_result_member( + **args, member_id=plan.members[0].member_id, chunks=chunks() + ) + ) + monkeypatch.setattr(transfer_space.shutil, "disk_usage", lambda _: SimpleNamespace(free=0)) + assert fixture.service.stage_result_manifest( + **args, manifest_payload=package.canonical_bytes + ).complete + assert asyncio.run( + fixture.service.upload_result_member( + **args, member_id=plan.members[0].member_id, chunks=chunks() + ) + ).complete + + +def test_source_route_preserves_range_and_releases_failed_request_reader(tmp_path): + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from k1link.web.observatory_worker_api import ( + ObservatoryWorkerAuthentication, + build_observatory_worker_router, + ) + + fixture = _fixture(tmp_path) + token = "synthetic-worker-token" * 3 + app = FastAPI() + app.include_router( + build_observatory_worker_router( + fixture.queue, + authentication=ObservatoryWorkerAuthentication( + bearer_token_sha256=hashlib.sha256(token.encode()).hexdigest(), + contour_id="worker-006", + ), + artifact_transport=fixture.service, + ) + ) + headers = { + "Authorization": "Bearer " + token, + "X-Mission-Core-Contour-Id": "worker-006", + "X-Mission-Core-Claim-Token": fixture.claim_token, + "X-Mission-Core-Claim-Generation": str(fixture.job.claim_generation), + } + prefix = "/api/v1/worker/observatory/recorded-jobs/" + fixture.job.job_id + with TestClient(app) as client: + manifest = client.get(prefix + "/source-materialization", headers=headers) + assert manifest.status_code == 200 + member = next(m for m in manifest.json()["members"] if m["kind"] == "spatial-replay") + response = client.get( + prefix + "/source-members/" + member["member_id"], + headers={**headers, "Range": "bytes=0-3"}, + ) + assert response.status_code == 206 and response.content == fixture.raw_path.read_bytes()[:4] + failed = client.get(prefix + "/source-members/" + "0" * 64, headers=headers) + assert failed.status_code == 409 + fixture.queue.fail( + fixture.job.job_id, + claim_token=fixture.claim_token, + error_code="test-completed", + message="Synthetic job closed", + ) + assert fixture.service.collect_source_copies()["retired"] == 1 diff --git a/tests/test_observatory_portable_lab_v1_promotion.py b/tests/test_observatory_portable_lab_v1_promotion.py index 1bf35757..db8ae8b1 100644 --- a/tests/test_observatory_portable_lab_v1_promotion.py +++ b/tests/test_observatory_portable_lab_v1_promotion.py @@ -9,11 +9,17 @@ from typing import cast import pytest REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -DEFINITIONS = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" -RUNTIME = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json" -PORTABLE_CONFIG = ( - REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json" +DEFINITIONS = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" ) +RUNTIME = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-worker-runtime-candidates.json" +) +PORTABLE_CONFIG = REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json" PROMOTION_SCRIPT = ( REPOSITORY_ROOT / "experiments" @@ -42,10 +48,7 @@ def _asset( ) -> dict[str, object]: return { "asset_id": asset_id, - "host_path": ( - "D:\\NDC_MISSIONCORE\\runtime\\assets\\observatory-portable\\" - + asset_id - ), + "host_path": ("D:\\NDC_MISSIONCORE\\runtime\\assets\\observatory-portable\\" + asset_id), "container_path": container_path, "kind": "tree" if tree else "file", "verification": "identity-sha256" if tree else "sha256", @@ -199,8 +202,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]: "component": "eomt", "status": "already-installed", "tag": ( - "ndc/mission-core-lab-v1-eomt-adapter:" - f"{component_source_revision[:12]}" + f"ndc/mission-core-lab-v1-eomt-adapter:{component_source_revision[:12]}" ), "base_image_sha256": ( "58df7489c3f2276f9591d500a012dee03e23d35543ce3c390b4c001e6bf90794" @@ -212,8 +214,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]: "component": "ddrnet", "status": "already-installed", "tag": ( - "ndc/mission-core-lab-v1-ddrnet-adapter:" - f"{component_source_revision[:12]}" + f"ndc/mission-core-lab-v1-ddrnet-adapter:{component_source_revision[:12]}" ), "base_image_sha256": ( "591cb382c099eeb05e7ec16e2371e0b2da54d2bb5c49ec0f4ac88dbf72b0f0cd" @@ -240,9 +241,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]: "staged_snapshot_sha256": "9" * 64, "staged_snapshot_file_count": 42, "staged_snapshot_byte_length": 4096, - "staged_snapshot_canonicalization": ( - "utf8-path-nul-length-nul-sha256-lf-v1" - ), + "staged_snapshot_canonicalization": ("utf8-path-nul-length-nul-sha256-lf-v1"), "embedded_snapshot_manifest_sha256": "a" * 64, "embedded_snapshot_manifest_byte_length": 8192, "python_dependency_bundle_sha256": "b" * 64, @@ -259,10 +258,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]: ), "derived_image_sha256": "c" * 64, "image": { - "tag": ( - "ndc/mission-core-observatory-worker-agent:" - f"{source_revision[:12]}" - ), + "tag": (f"ndc/mission-core-observatory-worker-agent:{source_revision[:12]}"), "id": f"sha256:{'c' * 64}", "size_bytes": 1_000_000, "thin_layer_bytes": 10_000, @@ -276,10 +272,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]: }, "runtime_contract": { "workdir": "/opt/nodedc/mission-core", - "pythonpath": ( - "/opt/nodedc/mission-core/src:" - "/opt/nodedc/mission-core/deps" - ), + "pythonpath": ("/opt/nodedc/mission-core/src:/opt/nodedc/mission-core/deps"), "entrypoint": [ "python3", "-m", diff --git a/tests/test_observatory_portable_lab_v1_worker_service.py b/tests/test_observatory_portable_lab_v1_worker_service.py index 040f0eea..84a3bfc1 100644 --- a/tests/test_observatory_portable_lab_v1_worker_service.py +++ b/tests/test_observatory_portable_lab_v1_worker_service.py @@ -43,7 +43,10 @@ from k1link.observatory.portable_worker_runtime import ( from k1link.observatory.worker_service import ObservatoryWorkerExecutorBuildContext REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -DEFINITIONS_PATH = REPOSITORY_ROOT / "config/observatory-portable-run-definitions.json" +DEFINITIONS_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab/observatory-portable-run-definitions.json" +) RELEASE_ID = "lab-v1-eomt-ddrnet-v1" RELEASE_SHA256 = "7" * 64 IMAGE_SHA256 = "8" * 64 @@ -76,10 +79,8 @@ class _Release: definition.setup_id != service_module.PORTABLE_LAB_V1_SETUP_ID or definition.definition_id != "lab-v1-eomt-ddrnet-portable" or definition.version != 2 - or definition.executable_contract_sha256 - != self.definition_contract_sha256 - or definition.result_contract.contract_sha256 - != self.result_contract_sha256 + or definition.executable_contract_sha256 != self.definition_contract_sha256 + or definition.result_contract.contract_sha256 != self.result_contract_sha256 ): raise ValueError("release belongs to another definition") @@ -241,17 +242,11 @@ def _image_build( component=component, base_image_sha256=BASE_IMAGE_SHA256S[component], derived_image_sha256=derived_image_sha256, - dockerfile_sha256=hashlib.sha256( - f"{component}:dockerfile".encode() - ).hexdigest(), - build_method=( - service_module.PORTABLE_LAB_V1_COMPONENT_IMAGE_BUILD_METHOD - ), + dockerfile_sha256=hashlib.sha256(f"{component}:dockerfile".encode()).hexdigest(), + build_method=(service_module.PORTABLE_LAB_V1_COMPONENT_IMAGE_BUILD_METHOD), installer_sha256=INSTALLER_SHA256, shared_adapter_sha256=hashlib.sha256(b"shared-adapter").hexdigest(), - component_adapter_sha256=hashlib.sha256( - f"{component}:adapter".encode() - ).hexdigest(), + component_adapter_sha256=hashlib.sha256(f"{component}:adapter".encode()).hexdigest(), ) @@ -318,9 +313,7 @@ def _composition_inputs( tmp_path, definition_sha256=definition.definition_sha256, ) - receipt = service_module.load_portable_lab_v1_worker_installation_receipt( - receipt_path - ) + receipt = service_module.load_portable_lab_v1_worker_installation_receipt(receipt_path) candidate = _runtime_candidate(definition, receipt) admission = PortableWorkerRuntimeAdmission( candidate_sha256=candidate.candidate_sha256, @@ -328,9 +321,7 @@ def _composition_inputs( blockers=(), assets=( PortableWorkerAssetVerification( - asset_id=( - service_module.PORTABLE_LAB_V1_WORKER_INSTALLATION_RECEIPT_ASSET_ID - ), + asset_id=(service_module.PORTABLE_LAB_V1_WORKER_INSTALLATION_RECEIPT_ASSET_ID), state="matched", reason=None, ), @@ -408,14 +399,10 @@ def test_receipt_loader_round_trips_full_runner_identity(tmp_path: Path) -> None receipt.runner_installation.eomt.image_sha256 ) assert receipt.ddrnet_image_build.network == "none" - assert receipt.ddrnet_image_build.build_method == ( - "docker-commit-exact-layer-v1" - ) + assert receipt.ddrnet_image_build.build_method == ("docker-commit-exact-layer-v1") assert receipt.ddrnet_image_build.installer_sha256 == INSTALLER_SHA256 assert receipt.installation_evidence_sha256 == "d" * 64 - assert receipt.runner_installation.definition_sha256 == ( - definition.definition_sha256 - ) + assert receipt.runner_installation.definition_sha256 == (definition.definition_sha256) assert tuple(asset.asset_id for asset in receipt.runner_installation.eomt.assets) == ( tuple(sorted(local_runners._EXPECTED_ASSET_TARGETS["eomt"])) ) @@ -519,9 +506,7 @@ def test_compose_returns_exact_lab_v1_builder_registration( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - definition, candidate, receipt, admission, installation = _composition_inputs( - tmp_path - ) + definition, candidate, receipt, admission, installation = _composition_inputs(tmp_path) captured: dict[str, object] = {} adapter = object() @@ -560,23 +545,15 @@ def test_compose_returns_exact_lab_v1_builder_registration( assert captured["definition"] is definition assert captured["admission"] is admission assert captured["installation"] is installation - assert captured["source_output_parent"] == ( - tmp_path / "lab-v1-portable/source-output" - ) - assert captured["eomt_runner"].__class__.__name__ == ( - "InstalledPortableLabV1EomtRunner" - ) - assert captured["ddrnet_runner"].__class__.__name__ == ( - "InstalledPortableLabV1DdrnetRunner" - ) + assert captured["source_output_parent"] == (tmp_path / "lab-v1-portable/source-output") + assert captured["eomt_runner"].__class__.__name__ == ("InstalledPortableLabV1EomtRunner") + assert captured["ddrnet_runner"].__class__.__name__ == ("InstalledPortableLabV1DdrnetRunner") def test_compose_fails_closed_on_changed_receipt_or_incomplete_admission( tmp_path: Path, ) -> None: - definition, candidate, receipt, admission, installation = _composition_inputs( - tmp_path - ) + definition, candidate, receipt, admission, installation = _composition_inputs(tmp_path) changed_path = _write_receipt( tmp_path, definition_sha256=definition.definition_sha256, @@ -596,9 +573,7 @@ def test_compose_fails_closed_on_changed_receipt_or_incomplete_admission( launcher=_Launcher(), ) - current = service_module.load_portable_lab_v1_worker_installation_receipt( - changed_path - ) + current = service_module.load_portable_lab_v1_worker_installation_receipt(changed_path) with pytest.raises( service_module.PortableLabV1WorkerCompositionError, match="does not seal its installation receipt", @@ -616,9 +591,7 @@ def test_compose_fails_closed_on_changed_receipt_or_incomplete_admission( tmp_path, definition_sha256=definition.definition_sha256, ) - restored = service_module.load_portable_lab_v1_worker_installation_receipt( - restored_path - ) + restored = service_module.load_portable_lab_v1_worker_installation_receipt(restored_path) release = cast(_Release, installation.release) uncovered_installation = cast( PortableLabV1ReleaseInstallation, diff --git a/tests/test_observatory_portable_queue_binding.py b/tests/test_observatory_portable_queue_binding.py index b66d71f2..8ec9c3c2 100644 --- a/tests/test_observatory_portable_queue_binding.py +++ b/tests/test_observatory_portable_queue_binding.py @@ -45,7 +45,11 @@ from k1link.sessions.models import ( ) REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +REGISTRY_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) SESSION_ID = "20260831T000000Z_viewer_live" CATALOG_SHA256 = "1" * 64 RAW_SHA256 = "2" * 64 diff --git a/tests/test_observatory_portable_result_publisher.py b/tests/test_observatory_portable_result_publisher.py index 0691ff5a..16e36959 100644 --- a/tests/test_observatory_portable_result_publisher.py +++ b/tests/test_observatory_portable_result_publisher.py @@ -66,7 +66,11 @@ from k1link.sessions import ( from k1link.web.observatory_api import build_observatory_router REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +REGISTRY_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) NOW = "2026-08-31T08:00:00.000Z" SOURCE_SESSION_ID = "20260831T075500Z_viewer_live" RESULT_ID = "portable-lab-result-001" @@ -746,7 +750,8 @@ def test_cache_does_not_hide_another_source_snapshot_or_profile_version(tmp_path def test_cache_survives_new_store_and_archive_reconciliation( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr("k1link.sessions.store.utc_now_iso", lambda: "2026-09-03T08:00:00.000Z") cache, queue, sessions, artifacts, registry, definition, job, _, _ = _cache_fixture(tmp_path) @@ -756,7 +761,10 @@ def test_cache_survives_new_store_and_archive_reconciliation( reopened = SessionStore(sessions.repository_root, data_dir=sessions.data_dir) reopened.reconcile_archive(_source_archive(tmp_path, definition)) cold_cache = PortableResultCache( - sessions=reopened, artifacts=artifacts, queue=queue, definitions=registry, + sessions=reopened, + artifacts=artifacts, + queue=queue, + definitions=registry, calculation_profiles=PortableCalculationProfileRegistry((_profile(definition),)), ) assert cold_cache.find(SOURCE_SESSION_ID, definition) == before @@ -928,3 +936,162 @@ def test_cache_api_existing_skips_source_preparation_submit_and_worker(tmp_path: request["idempotency_key"] = job.idempotency_key assert client.post("/api/v1/observatory/runs", json=request).status_code == 202 assert len(queue.list_jobs()) == 1 + + +def test_transport_retirement_survives_interruption_and_new_publisher(tmp_path, monkeypatch): + registry, definition, store, job, root = _fixture(tmp_path, extra_payload=b"keep-recording") + publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + paths = list((root / "artifacts").rglob("*")) + paths = [p for p in paths if p.is_file()] + assert len(paths) >= 2 + original = Path.unlink + deleted = [] + + def interrupted(path, *args, **kwargs): + if path in paths: + if deleted: + raise OSError("simulated closeout interruption") + deleted.append(path) + return original(path, *args, **kwargs) + + with monkeypatch.context() as m: + m.setattr(Path, "unlink", interrupted) + with pytest.raises(PortableResultPackageIntegrityError, match="retirement incomplete"): + publisher.publish(job=job, package_root=root) + assert (root / "retired-transport.json").is_file() + assert len(deleted) == 1 + new_publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + result = new_publisher.publish(job=job, package_root=root) + assert all(not p.exists() for p in paths) + assert new_publisher.publish(job=job, package_root=root).binding == result.binding + + +def test_transport_retirement_preserves_unknown_files_and_rejects_corrupt_retries(tmp_path): + registry, definition, store, job, root = _fixture(tmp_path) + publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + unknown = root / "operator-note.txt" + unknown.write_text("keep") + publisher.publish(job=job, package_root=root) + assert unknown.read_text() == "keep" + (root / "artifacts/result.json").write_text("corrupt") + with pytest.raises(PortableResultPackageIntegrityError, match="content changed"): + publisher.publish(job=job, package_root=root) + assert (root / "artifacts/result.json").read_text() == "corrupt" + + +def test_no_retirement_until_catalog_publication_succeeds(tmp_path, monkeypatch): + registry, definition, store, job, root = _fixture(tmp_path) + publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + + def fail(**kwargs): + raise ValueError("catalog unavailable") + + monkeypatch.setattr(store, "publish_lab_instance", fail) + with pytest.raises(PortableResultPackageIntegrityError): + publisher.publish(job=job, package_root=root) + assert (root / "artifacts/result.json").is_file() + assert not (root / "retired-transport.json").exists() + + +def test_retired_retry_requires_intact_archive(tmp_path): + registry, definition, store, job, root = _fixture(tmp_path) + publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + result = publisher.publish(job=job, package_root=root) + member = result.artifact_manifest.member("result-document") + archive = CentralArtifactStore(tmp_path / "central-artifacts") + archive.object_path(member.sha256).unlink() + with pytest.raises(PortableResultPackageIntegrityError): + publisher.publish(job=job, package_root=root) + assert (root / "retired-transport.json").exists() + + +def test_published_retry_preserves_original_time_profile_label_and_archive(tmp_path): + registry, definition, store, job, root = _fixture(tmp_path) + publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + first = publisher.publish(job=job, package_root=root) + acknowledged = replace(job, updated_at_utc="2026-09-01T08:00:00.000Z") + renamed = replace(_profile(definition), display_name="New presentation label") + restarted = _publisher( + tmp_path, store=store, registry=registry, profile=renamed, validator=_validator + ) + second = restarted.publish(job=acknowledged, package_root=root) + assert second == first + assert len(list((tmp_path / "central-artifacts/manifests").rglob("*.json"))) == 1 + + +def test_retire_published_historical_transfer_does_not_readmit_old_definition( + tmp_path, monkeypatch +): + registry, definition, store, job, root = _fixture(tmp_path) + publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + with monkeypatch.context() as m: + m.setattr(publisher, "_retire_transport", lambda *args: None) + published = publisher.publish(job=job, package_root=root) + current = PortableRunDefinitionRegistry.from_file( + REPOSITORY_ROOT / "config/observatory-portable-run-definitions.json" + ) + publisher._definitions = current + with pytest.raises(PortableResultPublicationBlockedError, match="not in the portable registry"): + publisher.publish(job=job, package_root=root) + with pytest.raises(PortableResultPublicationBlockedError, match="not durably published"): + publisher.retire_published_transport( + job=replace(job, publication_state="pending"), package_root=root + ) + assert (root / "artifacts/result.json").is_file() + completed = replace( + job, publication_state="published", publication_attempts=1, published_at_utc=NOW + ) + assert publisher.retire_published_transport(job=completed, package_root=root) == published + assert not (root / "artifacts/result.json").exists() + assert publisher.retire_published_transport(job=completed, package_root=root) == published + assert publisher._definitions is current + + +@pytest.mark.parametrize("damage", ["binding", "archive", "staging"]) +def test_historical_transfer_closeout_preserves_data_on_identity_failure( + tmp_path, monkeypatch, damage +): + registry, definition, store, job, root = _fixture(tmp_path) + publisher = _publisher( + tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator + ) + with monkeypatch.context() as m: + m.setattr(publisher, "_retire_transport", lambda *args: None) + published = publisher.publish(job=job, package_root=root) + if damage == "binding": + provenance = copy.deepcopy(published.binding.provenance) + provenance["job"]["job_id"] = "another-job" + with sqlite3.connect(store.database_path) as connection: + connection.execute( + "UPDATE observation_lab_instances SET provenance_json = ? WHERE session_id = ?", + (json.dumps(provenance), RESULT_ID), + ) + elif damage == "archive": + publisher._artifact_store.object_path( + published.artifact_manifest.member("result-document").sha256 + ).unlink() + else: + (root / "artifacts/result.json").write_bytes(b"changed") + with pytest.raises(PortableResultPackageIntegrityError): + publisher.retire_published_transport( + job=replace( + job, publication_state="published", publication_attempts=1, published_at_utc=NOW + ), + package_root=root, + ) + assert (root / "artifacts/result.json").is_file() + assert not (root / "retired-transport.json").exists() diff --git a/tests/test_observatory_portable_run_definitions.py b/tests/test_observatory_portable_run_definitions.py index 4a764b84..603c5d0a 100644 --- a/tests/test_observatory_portable_run_definitions.py +++ b/tests/test_observatory_portable_run_definitions.py @@ -18,7 +18,11 @@ from k1link.observatory.portable_run_definitions import ( ) REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +REGISTRY_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) DEFINITION_SHA256 = "269d71a24b4e63cff54e01273f9d4b35fc6cdd72bc6fadec206169ae0777e6ac" MODEL_MANIFEST_SHA256 = "3fd2d43af73bd73f89d9ffae95d8770cfdeb46033ec967509124fac6ae4afe56" M49_DEFINITION_SHA256 = "f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb" diff --git a/tests/test_observatory_portable_setup_api.py b/tests/test_observatory_portable_setup_api.py index 90316c01..c2a441d0 100644 --- a/tests/test_observatory_portable_setup_api.py +++ b/tests/test_observatory_portable_setup_api.py @@ -27,7 +27,11 @@ from k1link.sessions.models import SessionSummary from k1link.web.observatory_api import build_observatory_router REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +REGISTRY_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) SOURCE_SESSION_ID = "20260831T080000Z_viewer_live" diff --git a/tests/test_observatory_portable_setup_projection.py b/tests/test_observatory_portable_setup_projection.py index 40401ac0..7d874351 100644 --- a/tests/test_observatory_portable_setup_projection.py +++ b/tests/test_observatory_portable_setup_projection.py @@ -27,7 +27,11 @@ from k1link.observatory.source_admission import ( from k1link.sessions.models import SessionSummary REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +REGISTRY_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) RAV004_SESSION_ID = "20260828T130511Z_viewer_live" NEW_SESSION_ID = "20260831T080000Z_viewer_live" diff --git a/tests/test_observatory_portable_worker_integration.py b/tests/test_observatory_portable_worker_integration.py index d082d947..289ced0e 100644 --- a/tests/test_observatory_portable_worker_integration.py +++ b/tests/test_observatory_portable_worker_integration.py @@ -58,7 +58,11 @@ from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue from k1link.sessions import RecordedMediaInspector, SessionStore REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" +REGISTRY_PATH = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) def _definitions() -> PortableRunDefinitionRegistry: diff --git a/tests/test_observatory_portable_worker_runtime.py b/tests/test_observatory_portable_worker_runtime.py index 2d87c576..9bd85396 100644 --- a/tests/test_observatory_portable_worker_runtime.py +++ b/tests/test_observatory_portable_worker_runtime.py @@ -36,8 +36,16 @@ from k1link.observatory.worker_agent import ( ) REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -DEFINITION_REGISTRY = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json" -RUNTIME_REGISTRY = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json" +DEFINITION_REGISTRY = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-portable-run-definitions.json" +) +RUNTIME_REGISTRY = ( + REPOSITORY_ROOT + / "tests/fixtures/observatory/retired-fixed-lab" + / "observatory-worker-runtime-candidates.json" +) def _definitions() -> PortableRunDefinitionRegistry: diff --git a/tests/test_observatory_recorded_jobs.py b/tests/test_observatory_recorded_jobs.py index 06cfbcaa..df86becc 100644 --- a/tests/test_observatory_recorded_jobs.py +++ b/tests/test_observatory_recorded_jobs.py @@ -1648,3 +1648,58 @@ def test_simulation_and_recorded_claim_cannot_win_together(tmp_path): simulation = pool.submit(simulate) inference = pool.submit(recorded) assert simulation.result() != inference.result() + + +def test_hidden_failed_attempt_keeps_audit_and_rejects_active_work(tmp_path: Path) -> None: + queue = _queue(tmp_path) + job, claim = _running_job(queue) + with pytest.raises(ObservatoryRecordedQueueConflictError): + queue.hide_failed_projection(job.job_id) + failed = queue.fail( + job.job_id, + claim_token=claim.claim_token, + error_code="executor-error", + message="prepare failed", + ) + queue.hide_failed_projection(job.job_id) + queue.hide_failed_projection(job.job_id) + assert queue.get(job.job_id) == failed + assert queue.list_jobs(include_hidden=False) == () + assert queue.list_jobs() == (failed,) + assert _queue(tmp_path).list_jobs(include_hidden=False) == () + + +@pytest.mark.parametrize( + "state,publication,protected", + [ + ("accepted", "not-required", True), + ("queued", "not-required", True), + ("claimed", "not-required", True), + ("running", "not-required", True), + ("paused", "not-required", True), + ("preemption-pending", "not-required", True), + ("reconciliation-required", "not-required", True), + ("failed", "not-required", False), + ("succeeded", "pending", True), + ("succeeded", "failed", True), + ("succeeded", "published", False), + ], +) +def test_source_consumers_include_hidden_and_pending_states( + tmp_path, state, publication, protected +): + queue = _queue(tmp_path) + intent = _intent() + job, _ = queue.submit(intent) + # Exercise the SQL ownership query against every durable state, including + # records hidden from UI. No truncated history list is used for liveness. + with sqlite3.connect(tmp_path / RECORDED_JOB_DATABASE_NAME) as connection: + connection.execute( + "UPDATE observatory_recorded_jobs SET state=?, publication_state=? WHERE job_id=?", + (state, publication, job.job_id), + ) + connection.execute( + "INSERT INTO observatory_hidden_job_projections VALUES (?, ?)", (job.job_id, NOW) + ) + assert queue.has_source_consumers([intent.source_session_id]) is protected + assert not queue.has_source_consumers(["unrelated-source"]) diff --git a/tests/test_observatory_transfer_storage.py b/tests/test_observatory_transfer_storage.py new file mode 100644 index 00000000..cd5ea5cd --- /dev/null +++ b/tests/test_observatory_transfer_storage.py @@ -0,0 +1,232 @@ +from __future__ import annotations + +import asyncio +import hashlib +import json +import os +import subprocess +import sys +from types import SimpleNamespace + +import pytest + +from k1link.observatory import transfer_space as capacity +from k1link.observatory.source_transport_lifecycle import SourceCopy, SourceTransportLifecycle +from k1link.web.source_transfer_response import SourceTransferFileResponse + + +def test_large_multicomponent_transfers_use_actual_space_and_share_reservations( + tmp_path, monkeypatch +): + gib = 1024**3 + free = [40 * gib] + monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=free[0])) + inputs, results = tmp_path / "inputs", tmp_path / "results" + inputs.mkdir() + results.mkdir() + first = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=2 * gib) + second = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=2 * gib) + with first.reservation(inputs, 20 * gib) as upload: + with second.reservation(results, 16 * gib): + with pytest.raises(capacity.TransferCapacityError): + first.check(inputs, 3 * gib) + # Written bytes already reduce disk free; don't double count them. + free[0] -= 12 * gib + upload.written(12 * gib) + first.check(inputs, 2 * gib) + first.check(inputs, 18 * gib) + assert not list(first.root.glob("reservation-*.json")) + + +def test_reservation_survives_await_and_releases_on_cancel(tmp_path, monkeypatch): + monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100)) + service = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=10) + + async def upload(): + with service.reservation(tmp_path, 80): + await asyncio.sleep(0) + with pytest.raises(capacity.TransferCapacityError): + service.check(tmp_path, 11) + raise asyncio.CancelledError() + + with pytest.raises(asyncio.CancelledError): + asyncio.run(upload()) + service.check(tmp_path, 90) + + +def test_dead_process_reservation_recovers_without_deleting_partial_data(tmp_path, monkeypatch): + script = """import os,sys +from pathlib import Path +from k1link.observatory.transfer_space import TransferSpace +p=Path(sys.argv[1]) +with TransferSpace(p/'ledger',reserve_bytes=0).reservation(p,1000): + (p/'partial').write_bytes(b'recover me') + os._exit(0) +""" + subprocess.run([sys.executable, "-c", script, str(tmp_path)], check=True, timeout=10) + assert len(list((tmp_path / "ledger").glob("reservation-*.json"))) == 1 + monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100)) + capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=10).check(tmp_path, 90) + assert (tmp_path / "partial").read_bytes() == b"recover me" + assert not list((tmp_path / "ledger").glob("reservation-*.json")) + + +def test_other_process_live_reservation_is_counted(tmp_path, monkeypatch): + script = """import sys +from pathlib import Path +from k1link.observatory.transfer_space import TransferSpace +p=Path(sys.argv[1]) +with TransferSpace(p/'ledger',reserve_bytes=0).reservation(p,80): + print('ready',flush=True) + sys.stdin.readline() +""" + child = subprocess.Popen( + [sys.executable, "-c", script, str(tmp_path)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + try: + assert child.stdout.readline().strip() == "ready" + monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100)) + with pytest.raises(capacity.TransferCapacityError): + capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=10).check(tmp_path, 11) + finally: + child.communicate("done\n", timeout=10) + + +def test_torn_dead_reservation_recovers_but_unknown_files_stay(tmp_path, monkeypatch): + service = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=0) + torn = service.root / ("reservation-" + "a" * 32 + ".json") + torn.write_bytes(b'{"version":') + unknown = service.root / "unrelated-evidence.json" + unknown.write_text("preserve") + monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100)) + service.check(tmp_path, 100) + assert not torn.exists() and unknown.read_text() == "preserve" + + +def _copies(tmp_path, consumers=None): + original = tmp_path / "original" + original.write_bytes(b"immutable recording") + root = tmp_path / "cas" + root.mkdir() + copy = root / "copy" + copy.write_bytes(original.read_bytes()) + digest = hashlib.sha256(original.read_bytes()).hexdigest() + service = SourceTransportLifecycle(root, consumers or (lambda _: False)) + with service.reading(): + service.register( + SourceCopy(copy, digest, copy.stat().st_size), + sources=[SourceCopy(original, digest, original.stat().st_size)], + session_id="recording-one", + ) + return service, original, copy + + +def test_all_shared_consumers_and_readers_must_finish(tmp_path): + pending = {"recording-one", "recording-two"} + service, original, copy = _copies( + tmp_path, lambda sessions: bool(pending.intersection(sessions)) + ) + digest = hashlib.sha256(original.read_bytes()).hexdigest() + with service.reading(): + service.register( + SourceCopy(copy, digest, copy.stat().st_size), + sources=[SourceCopy(original, digest, original.stat().st_size)], + session_id="recording-two", + ) + pending.remove("recording-one") + assert service.collect()["protected"] == 1 + pending.clear() + with service.reading(): + assert service.collect()["reading"] == 1 + assert copy.exists() + unknown = service.root / "old-unknown" + unknown.write_bytes(b"keep") + result = service.collect() + assert result["retired"] == 1 and result["bytes"] == len(original.read_bytes()) + assert original.exists() and unknown.exists() and not copy.exists() + assert service.collect()["bytes"] == 0 + + +@pytest.mark.parametrize( + "damage", ["missing_original", "changed_original", "changed_copy", "symlink", "hardlink"] +) +def test_unproven_recovery_and_shared_files_are_preserved(tmp_path, damage): + service, original, copy = _copies(tmp_path) + if damage == "missing_original": + original.unlink() + elif damage == "changed_original": + original.write_bytes(b"different recording") + elif damage == "changed_copy": + copy.write_bytes(b"different recording") + elif damage == "symlink": + copy.unlink() + copy.symlink_to(original) + else: + os.link(copy, tmp_path / "another-owner") + assert service.collect()["unverified"] == 1 + assert copy.exists() + + +def test_retirement_recovers_after_unlink_before_receipt(tmp_path): + service, original, copy = _copies(tmp_path) + path = next(service.ledger.glob("*.json")) + row = json.loads(path.read_bytes()) + row["state"] = "retiring" + path.write_text(json.dumps(row)) + copy.unlink() + assert service.collect()["retired"] == 1 + assert original.exists() + assert json.loads(path.read_bytes())["state"] == "retired" + + +def test_explicit_cleanup_scope_never_retires_other_registered_copies(tmp_path): + service, original, selected = _copies(tmp_path) + other = service.root / "other-registered" + other.write_bytes(original.read_bytes()) + digest = hashlib.sha256(original.read_bytes()).hexdigest() + with service.reading(): + service.register( + SourceCopy(other, digest, other.stat().st_size), + sources=[SourceCopy(original, digest, original.stat().st_size)], + session_id="recording-two", + ) + assert service.collect(only_paths=[selected])["retired"] == 1 + assert not selected.exists() and other.exists() and original.exists() + assert service.collect(only_paths=[])["retired"] == 0 + assert other.exists() + + +@pytest.mark.parametrize("disconnect", [False, True]) +def test_http_reader_is_held_until_range_finishes_even_on_disconnect(tmp_path, disconnect): + service, original, copy = _copies(tmp_path) + response = SourceTransferFileResponse(copy) + response.lease_fd = service.acquire_reader() + messages = [] + + async def send(message): + assert service.collect()["reading"] == 1 + messages.append(message) + if disconnect: + raise ConnectionError("viewer disconnected") + + async def receive(): + return {"type": "http.disconnect"} + + scope = { + "type": "http", + "method": "GET", + "headers": [(b"range", b"bytes=0-3")], + "extensions": {"http.response.pathsend": {}}, + } + if disconnect: + with pytest.raises(ConnectionError): + asyncio.run(response(scope, receive, send)) + else: + asyncio.run(response(scope, receive, send)) + assert messages[0]["status"] == 206 + assert messages[-1]["body"] == original.read_bytes()[:4] + assert not any(m["type"] == "http.response.pathsend" for m in messages) + assert service.collect()["retired"] == 1 diff --git a/tests/test_session_api.py b/tests/test_session_api.py index 0c67534c..b2ada6ae 100644 --- a/tests/test_session_api.py +++ b/tests/test_session_api.py @@ -454,7 +454,7 @@ def test_session_router_versions_capability_and_calculation_profile_projections( ) -def test_observatory_projection_api_renames_alias_and_deletes_only_projection( +def test_observatory_projection_api_rename_and_delete_require_storage_service( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -553,16 +553,16 @@ def test_observatory_projection_api_renames_alias_and_deletes_only_projection( assert store.get_session(projection.session_id).summary.display_name == "Маршрут у школы" deleted = client.delete(url) - assert deleted.status_code == 204 - assert deleted.content == b"" - assert client.delete(url).status_code == 404 + assert deleted.status_code == 503 + assert client.delete(url).status_code == 503 + assert store.get_lab_instance(projection.session_id) is not None assert store.get_session_with_catalog_snapshot(source.name)[1] == source_snapshot assert hashlib.sha256(source_payload.read_bytes()).hexdigest() == source_payload_sha256 assert source.is_dir() assert cache_sentinel.read_bytes() == b"must-not-be-touched" -def test_observatory_projection_api_rejects_source_and_legacy_lab( +def test_observatory_projection_api_protects_source_and_supports_legacy_catalog( tmp_path: Path, ) -> None: repository = tmp_path / "repo" @@ -588,14 +588,16 @@ def test_observatory_projection_api_rejects_source_and_legacy_lab( "display_name": "Нельзя изменить", } - for session_id in (source.name, legacy.session_id): - url = f"/api/v1/observatory/lab-projections/{session_id}" - assert client.patch(url, json=rename_document).status_code == 409 - assert client.delete(url).status_code == 409 + url = f"/api/v1/observatory/lab-projections/{source.name}" + assert client.patch(url, json=rename_document).status_code == 409 + assert client.delete(url).status_code == 409 + legacy_url = f"/api/v1/observatory/lab-projections/{legacy.session_id}" + assert client.patch(legacy_url, json=rename_document).status_code == 200 + assert client.delete(legacy_url).status_code == 503 assert source.is_dir() assert store.get_session(source.name).summary.session_id == source.name - assert store.get_session(legacy.session_id).summary.display_name == "LAB E21 · legacy API row" + assert store.get_session(legacy.session_id).summary.display_name == "Нельзя изменить" def test_delete_session_removes_evidence_and_cache_but_refuses_an_open_recording( @@ -3257,3 +3259,61 @@ def test_layout_get_migrates_legacy_tool_windows_out_of_the_contract(tmp_path: P assert loaded["version"] == 2 assert "tool_windows" not in loaded + + +def test_worker_perception_preserves_playback_and_has_no_local_fallback(tmp_path): + import httpx + + from k1link.laboratory.worker_gateway import ( + LaboratoryGatewayConfiguration, + LaboratoryWorkerGateway, + ) + + repository = tmp_path / "repo" + sessions = repository / "sessions" + session = make_legacy_session(sessions, "20260716T205632Z_viewer_live") + store = SessionStore(repository, data_dir=tmp_path / "data") + store.reconcile_archive(xgrids_k1_archive_source(sessions)) + token = tmp_path / "token" + token.write_text("b" * 48) + calls = [] + + def remote(request): + calls.append(request) + if request.method == "POST": + assert json.loads(request.content)["recording_id"] == "recording-001" + return httpx.Response(200, content=b"RRF2complete-playback") + assert request.headers["range"] == "bytes=4-8" + return httpx.Response(206, content=b"movie", headers={"content-range": "bytes 4-8/50"}) + + class LocalMustNotRun: + def render(self, *args, **kwargs): + raise AssertionError("Operator attempted LAB execution") + def video(self, *args, **kwargs): + raise AssertionError("Operator opened working data") + + gateway = LaboratoryWorkerGateway( + LaboratoryGatewayConfiguration("http://127.0.0.1:19087", token), + transport=httpx.MockTransport(remote), + ) + app = FastAPI() + app.include_router(build_session_router( + store, laboratory_gateway=gateway, perception_overlay_provider=LocalMustNotRun(), + perception_media_provider=LocalMustNotRun(), + )) + with TestClient(app) as client: + prefix = f"/api/v1/observation-sessions/{session.name}" + r = client.post(prefix + "/perception.rrd", json={ + "application_id": "nodedc_mission_core_recorded", "recording_id": "recording-001"}) + assert r.status_code == 200 and r.content == b"RRF2complete-playback" + r = client.get(prefix + "/perception-media/result-test/recording.mp4?generation=abc", + headers={"Range": "bytes=4-8"}) + assert r.status_code == 206 and r.content == b"movie" + assert calls[-1].url.path.endswith("/perception-media/result-test/recording.mp4") + assert calls[-1].url.query == b"generation=abc" + gateway.configuration = None + response = client.post(prefix + "/perception.rrd", json={ + "application_id": "nodedc_mission_core_recorded", "recording_id": "recording-001", + }) + assert response.status_code == 503 + assert len(calls) == 2 diff --git a/tests/test_session_store.py b/tests/test_session_store.py index 76604086..ca972619 100644 --- a/tests/test_session_store.py +++ b/tests/test_session_store.py @@ -1461,7 +1461,7 @@ def test_capability_projection_delete_removes_only_catalog_projection( ).fetchone()[0] == 0 -def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows( +def test_lab_projection_mutations_admit_legacy_but_reject_source_and_corrupt_rows( tmp_path: Path, ) -> None: repository = tmp_path / "repo" @@ -1539,7 +1539,14 @@ def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows( ) connection.commit() - for session_id in (source.name, legacy.session_id, corrupt.session_id): + with sqlite3.connect(store.database_path) as connection: + connection.execute( + "UPDATE observation_lab_instances SET include_recorded_media = NULL " + "WHERE session_id = ?", + (legacy.session_id,), + ) + + for session_id in (source.name, corrupt.session_id): with pytest.raises(SessionIntegrityError, match="capability-owned"): store.rename_capability_lab_projection(session_id, "Нельзя изменить") with pytest.raises(SessionIntegrityError, match="capability-owned"): @@ -1551,7 +1558,11 @@ def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows( store.delete_capability_lab_projection(mismatch.session_id) assert store.get_session(source.name).summary.session_id == source.name - assert store.get_session(legacy.session_id).summary.display_name == "LAB E21 · legacy" + assert store.rename_capability_lab_projection(legacy.session_id, "Архив") == "Архив" + store.delete_capability_lab_projection(legacy.session_id) + with pytest.raises(SessionNotFoundError): + store.get_session(legacy.session_id) + assert source.is_dir() with sqlite3.connect(store.database_path) as connection: retained_ids = { row[0] @@ -1561,7 +1572,6 @@ def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows( } assert { source.name, - legacy.session_id, corrupt.session_id, mismatch.session_id, } <= retained_ids