diff --git a/docs/SIMULATION_WORKFLOW.md b/docs/SIMULATION_WORKFLOW.md index e661e7fd..6c2d7c5f 100644 --- a/docs/SIMULATION_WORKFLOW.md +++ b/docs/SIMULATION_WORKFLOW.md @@ -202,3 +202,21 @@ profile-permitted surface, detection and observed LiDAR returns. See for deployment, visual acceptance and the reproduced 310 m mission failure. The long mission is not qualified: incorrect/low-confidence surface labels leave no full-width local support after approximately six metres. + +## Gaussian import source ownership (2026-11-07) + +Manual LCC/LCC2 imports now require a reachable provider with durable source +retention. Core stages originals only until Worker verifies and retains them. +Worker owns originals independently of conversion jobs; Core retains the optimized +scene and project/edit metadata. Rebuilds use Worker receipts. The analysis archive +compatibility route streams from Worker without downloading a local disk copy. +See [storage retention](STORAGE_RETENTION.md#imported-scan-originals--owner-amendment-2026-11-07). +Onboard direct upload remains outside this implementation. + +Legacy ready projects can be adopted through `POST /projects/{id}/source/retain` +without rebuilding or changing scene IDs. It discovers the Worker original, +verifies every imported file and pins normalized archive members independently. +An explicit matching receipt can complete an old incomplete upload first. +An archive already absent because of the retired capacity-eviction logic is +adopted only after fresh Worker hash verification against the original manifest; +this does not count as newly freed local space. diff --git a/docs/STORAGE_RETENTION.md b/docs/STORAGE_RETENTION.md index 96d3889a..d207a728 100644 --- a/docs/STORAGE_RETENTION.md +++ b/docs/STORAGE_RETENTION.md @@ -267,3 +267,38 @@ scripts have no universal disk quota: they must implement the declared capture bound and perform closeout. Existing cache quotas and service-log rotation keep their separate writer-owned enforcement. This amendment does not claim that a filesystem-wide automatic limit or remote Worker cleanup has been installed. + +## Imported scan originals — owner amendment, 2026-11-07 + +For manual Gaussian LCC/LCC2 folder and ZIP/RAR/7z imports, Mission Core owns +**temporary transfer staging**, not permanent original storage. An available +Gaussian provider advertising `durable-source/v1` is required before allocating +an upload project. An outage mid-transfer preserves unfinished staging for retry. +On complete transfer the provider verifies every admitted original by size and +SHA-256, flushes the bytes and publishes an independent retention receipt. +Core persists that receipt, freshly verifies remote hashes and its local hashes, +journals `verified → retiring → remote`, and removes only the declared local +source files. Interrupted retirement resumes using that persisted receipt. +There is no low-disk exception that deletes an unverified archive. + +Conversion then runs from Worker storage. Its failure, job cancellation or job +removal does not remove retained originals. Retry uses the receipt; no full local +fallback copy is created. Core keeps optimized SOG/LOD/collision artifacts, +source identity/receipt, small optional trajectory metadata, and application edits. +The user's original file outside the imported project's source directory is not +part of staging and is never deleted by this workflow. + +Older ready projects can be migrated with +`POST /api/v1/simulation-worlds/projects/{id}/source/retain`. The endpoint verifies +that the existing provider job includes **every** imported file, retains it, +then retires staging without changing the world manifest, source bundle identity, +viewer settings, artifacts or semantic map. Legacy archives are resolved through the matching Worker ingest record and their +original upload descriptor; missing or mismatched ownership is refused. An old job ID alone never authorizes deletion. + +Provider receipts and pins live in the existing persistent Gaussian data volume, +independent of containers/jobs. Migration needs the entire volume, configuration, +secrets and compatible executor, not just a Docker image. Provider address is a +hint; receipt identity and hashes permit relocation to a different host. See the +provider repository `docs/SOURCE_RETENTION.md` for its API and portability boundary. +This supersedes local-original retention for this narrowly defined import flow; +other recordings, unique evidence and application data remain protected above. diff --git a/src/k1link/simulation/ai_polygon/project_worlds.py b/src/k1link/simulation/ai_polygon/project_worlds.py index 556f5e55..fc378edf 100644 --- a/src/k1link/simulation/ai_polygon/project_worlds.py +++ b/src/k1link/simulation/ai_polygon/project_worlds.py @@ -120,7 +120,10 @@ class ProjectWorlds: if not 0 < item["byte_length"] <= 16 * 1024**2: raise ValueError("Trajectory exceeds analysis transport budget") root = self.projects.source_root(project["project_id"]).resolve() - path = root / item["logical_path"] + path = (root.parent / "metadata" / "poses.json" + if source.get("storage", {}).get("local_state") in {"retiring", "remote"} + else root / item["logical_path"]) + root = root.parent if source.get("storage") else root if path.is_symlink() or not path.resolve().is_relative_to(root): raise ValueError("Trajectory escaped its project") raw = path.read_bytes() @@ -130,6 +133,16 @@ class ProjectWorlds: base64=base64.b64encode(raw).decode("ascii")) return result + def remote_analysis_archive(self, world): + """Return a verified Worker receipt, never a local original fallback copy.""" + project = self.projects.get(world["storage"]["project_id"]) + if self.world(project)["sha256"] != world["sha256"]: + raise ValueError("Gaussian project changed") + source = project["source"] + if source["kind"] != "archive" or not source.get("storage"): + return None + return source["storage"]["receipt"] + def analysis_archive(self, world): """Serve only the original archive belonging to this exact world.""" project = self.projects.get(world["storage"]["project_id"]) diff --git a/src/k1link/simulation/gaussian_pipeline_gateway.py b/src/k1link/simulation/gaussian_pipeline_gateway.py index 5aa98f2c..3b948a93 100644 --- a/src/k1link/simulation/gaussian_pipeline_gateway.py +++ b/src/k1link/simulation/gaussian_pipeline_gateway.py @@ -7,7 +7,7 @@ import hashlib import json import os import re -from collections.abc import Mapping +from collections.abc import Iterator, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any, Final @@ -172,6 +172,7 @@ class GaussianPipelineGateway: *, entrypoint: str, source_format: str, + additional_paths: list[str] | None = None, ) -> GaussianSourceBundleUpload: if source_format not in {"lcc", "lcc2"}: raise GaussianPipelineIntegrityError("Gaussian source format must be lcc or lcc2") @@ -186,7 +187,10 @@ class GaussianPipelineGateway: "Gaussian source bundle root must be one regular directory" ) root = root_candidate.resolve() - logical_paths = _discover_bundle_members(root, logical_entrypoint, source_format) + logical_paths = set(_discover_bundle_members(root, logical_entrypoint, source_format)) + logical_paths.update( + _logical_path(item, "source member") for item in (additional_paths or []) + ) local_members: list[tuple[str, Path, str, int]] = [] total_byte_length = 0 for logical_path in sorted(logical_paths, key=lambda value: value.encode("utf-8")): @@ -294,6 +298,52 @@ class GaussianPipelineGateway: ) return _source_bundle_upload(document.get("source")) + def require_source_retention(self) -> None: + if self.capabilities().get("source_retention") != "durable-source/v1": + raise GaussianPipelineGatewayError( + "Worker не поддерживает постоянное хранение исходников. Обновите Gaussian Pipeline." + ) + + def retain_source(self, original: dict[str, Any]) -> dict[str, Any]: + from k1link.simulation.source_retention import validate_receipt + receipt = self._json("POST", "/v1/sources", document=original, + timeout_seconds=self.ingest_timeout_seconds) + validate_receipt(receipt, expected=original) + return receipt + + def retained_source(self, receipt: dict[str, Any], *, verify: bool = False) -> dict[str, Any]: + from k1link.simulation.source_retention import validate_receipt + validate_receipt(receipt) + suffix = "?verify=sha256" if verify else "" + current = self._json("GET", f"/v1/sources/{receipt['source_id']}{suffix}", + timeout_seconds=self.ingest_timeout_seconds) + validate_receipt(current, expected=receipt["input"]) + if current["source_id"] != receipt["source_id"]: + raise GaussianPipelineIntegrityError("Worker source receipt changed") + return current + + def job_original_source(self, job_id: str) -> dict[str, Any]: + return self._json("GET", f"/v1/jobs/{quote(job_id, safe='')}/source") + + def stream_retained_archive(self, receipt: dict[str, Any]) -> Iterator[bytes]: + """Compatibility transport for existing analysis clients; no disk staging.""" + import hashlib + self.retained_source(receipt) + archive = receipt["input"]["archive"] + with self._client.stream("GET", f"/v1/sources/{receipt['source_id']}/archive", + timeout=self.ingest_timeout_seconds) as response: + response.raise_for_status() + digest = hashlib.sha256() + length = 0 + for chunk in response.iter_bytes(1024 * 1024): + length += len(chunk) + if length > archive["byte_length"]: + raise GaussianPipelineIntegrityError("Worker archive size changed") + digest.update(chunk) + yield chunk + if length != archive["byte_length"] or digest.hexdigest() != archive["sha256"]: + raise GaussianPipelineIntegrityError("Worker archive integrity mismatch") + def _upload_member( self, source: Path, diff --git a/src/k1link/simulation/projects.py b/src/k1link/simulation/projects.py index a50ab2a3..70a69364 100644 --- a/src/k1link/simulation/projects.py +++ b/src/k1link/simulation/projects.py @@ -25,7 +25,6 @@ from k1link.simulation.gaussian_pipeline_gateway import ( GaussianPipelineGatewayError, GaussianPipelineUnavailableError, configured_gaussian_pipeline_gateway, - discover_gaussian_source_bundle, is_xgrids_source_mesh_path, ) @@ -296,6 +295,16 @@ class SimulationProjectStore: self._write(document) return document + def update_source_storage(self, project_id: str, **fields: Any) -> dict[str, Any]: + if set(fields) - {"storage", "prepared_receipt"}: + raise SimulationProjectError("invalid source storage fields") + with self._lock: + document = self._read(project_id) + document["source"].update(fields) + document["updated_at_utc"] = utc_now_iso() + self._write(document) + return document + def update_processing( self, project_id: str, @@ -446,6 +455,12 @@ class SimulationProjectStore: stream.flush() os.fsync(stream.fileno()) temporary.replace(destination) + if os.name != "nt": + directory_fd = os.open(destination.parent, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) def _project_root(self, project_id: str) -> Path: if PROJECT_ID_PATTERN.fullmatch(project_id) is None: @@ -528,6 +543,47 @@ class SimulationProjectService: self._cancel_events.pop(project_id, None) self._condition.notify_all() + def retain_originals( + self, project_id: str, receipt: dict[str, Any] | None = None + ) -> dict[str, Any]: + """Migrate a ready project without rebuilding or changing its world.""" + from k1link.simulation.source_retention import confirm_storage, retire_local_source + project = self.store.get(project_id) + if project["status"] != "ready": + raise SimulationProjectConflictError("Завершите сборку перед переносом исходников.") + provider = self.provider_factory() + if provider is None: + raise GaussianPipelineUnavailableError("Worker недоступен.") + try: + provider.require_source_retention() + if not project["source"].get("storage"): + job_id = project["provider"]["job_id"] + if receipt is None: + original = provider.job_original_source(job_id) + receipt = provider.retain_source(original) + if project["source"]["kind"] == "archive": + job = provider.get_job(job_id) + prepared = provider.retain_source( + {"kind": "folder", "source": job["request"]["source"]} + ) + self.store.update_source_storage(project_id, prepared_receipt=prepared) + confirm_storage(self.store, project_id, provider, receipt) + retire_local_source(self.store, project_id, provider) + return self.store.get(project_id) + finally: + provider.close() + + def require_import_worker(self) -> None: + provider = self.provider_factory() + if provider is None: + raise GaussianPipelineUnavailableError( + "Worker недоступен. Включите Worker и повторите загрузку." + ) + try: + provider.require_source_retention() + finally: + provider.close() + def begin_build(self, project_id: str) -> dict[str, Any]: project = self.store.get(project_id) if project.get("status") == "failed": @@ -573,6 +629,8 @@ class SimulationProjectService: "Gaussian Pipeline недоступен для повторной сборки." ) try: + from k1link.simulation.source_retention import prepare_source + prepare_source(self.store, project_id, provider) _retry_provider_unavailable(lambda: provider.delete_job(job_id)) finally: provider.close() @@ -597,20 +655,8 @@ class SimulationProjectService: raise SimulationProjectError( "Активная Gaussian-сборка потеряла provider job id после перезапуска." ) - source_root = self.store.source_root(project_id) - if project["source"]["kind"] == "archive": - source_file = project["source"]["files"][0] - archive = provider.upload_source_archive( - _confined_path(source_root, str(source_file["logical_path"])) - ) - source = provider.normalize_archive(archive) - else: - entrypoint, source_format = discover_gaussian_source_bundle(source_root) - source = provider.upload_source_bundle( - source_root, - entrypoint=entrypoint, - source_format=source_format, - ) + from k1link.simulation.source_retention import prepare_source + source = prepare_source(self.store, project_id, provider) source_mesh_available = any( is_xgrids_source_mesh_path(member.logical_path) for member in source.members @@ -759,38 +805,6 @@ class SimulationProjectService: available_bytes = shutil.disk_usage(artifacts_root).free if available_bytes >= required_bytes: return - project = self.store.get(project_id) - source = project.get("source") - provider = project.get("provider") - if ( - isinstance(source, dict) - and source.get("kind") == "archive" - and isinstance(provider, dict) - and isinstance(provider.get("job_id"), str) - ): - source_files = source.get("files") - if isinstance(source_files, list) and len(source_files) == 1: - source_file = source_files[0] - if isinstance(source_file, dict): - logical_path = source_file.get("logical_path") - byte_length = source_file.get("byte_length") - if isinstance(logical_path, str) and isinstance(byte_length, int): - source_path = _confined_path( - self.store.source_root(project_id), - logical_path, - ) - try: - source_stat = source_path.stat() - except OSError: - source_stat = None - if ( - source_stat is not None - and source_path.is_file() - and not source_path.is_symlink() - and source_stat.st_size == byte_length - ): - source_path.unlink() - available_bytes = shutil.disk_usage(artifacts_root).free if available_bytes < required_bytes: raise SimulationProjectError( "Недостаточно места для импорта Gaussian-мира: " @@ -823,6 +837,8 @@ class SimulationProjectService: "Gaussian Pipeline недоступен для удаления серверных артефактов." ) try: + if project["source"].get("storage"): + provider.require_source_retention() provider.delete_job(job_id) except GaussianPipelineGatewayError: with suppress(SimulationProjectError): diff --git a/src/k1link/simulation/source_retention.py b/src/k1link/simulation/source_retention.py new file mode 100644 index 00000000..0f2aa221 --- /dev/null +++ b/src/k1link/simulation/source_retention.py @@ -0,0 +1,227 @@ +"""Verified Worker ownership of originals, followed by journaled local eviction.""" + +from __future__ import annotations + +import hashlib +import os +import re +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from k1link.simulation.gaussian_pipeline_gateway import ( + GaussianArchiveUpload, + GaussianPipelineIntegrityError, + GaussianSourceBundleUpload, + _source_bundle_upload, + discover_gaussian_source_bundle, +) + +if TYPE_CHECKING: + from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineGateway + from k1link.simulation.projects import SimulationProjectStore + + +def validate_receipt(value: Any, *, expected: dict[str, Any] | None = None) -> None: + if ( + not isinstance(value, dict) + or value.get("schema_version") != "gaussian-pipeline.source-receipt/v1" + or value.get("retention") != "independent-of-jobs" + or not re.fullmatch(r"src-[a-f0-9]{64}", str(value.get("source_id"))) + or not isinstance(value.get("verified_at_utc"), str) + ): + raise GaussianPipelineIntegrityError("Worker did not confirm durable source storage") + original = value.get("input") + if not isinstance(original, dict): + raise GaussianPipelineIntegrityError("Worker source identity missing") + if original.get("kind") == "folder": + _source_bundle_upload(original.get("source")) + elif original.get("kind") == "archive": + archive = original.get("archive") + if ( + not isinstance(archive, dict) + or not re.fullmatch(r"[a-zA-Z0-9_-]+", str(archive.get("upload_id"))) + or archive.get("format") not in {"zip", "rar", "7z"} + or not re.fullmatch(r"[a-f0-9]{64}", str(archive.get("sha256"))) + or not isinstance(archive.get("byte_length"), int) + or archive["byte_length"] <= 0 + or not isinstance(archive.get("archive_name"), str) + or Path(archive["archive_name"]).name != archive["archive_name"] + ): + raise GaussianPipelineIntegrityError("Worker archive receipt invalid") + else: + raise GaussianPipelineIntegrityError("Worker source kind invalid") + if expected is not None and original != expected: + raise GaussianPipelineIntegrityError("Worker retained different source files") + + +def receipt_files(receipt: dict[str, Any]) -> dict[str, tuple[int, str]]: + validate_receipt(receipt) + original = receipt["input"] + if original["kind"] == "archive": + archive = original["archive"] + return {archive["archive_name"]: (archive["byte_length"], archive["sha256"])} + return { + f["logical_path"]: (f["byte_length"], f["sha256"]) for f in original["source"]["members"] + } + + +def confirm_storage( + store: SimulationProjectStore, + project_id: str, + provider: GaussianPipelineGateway, + receipt: dict[str, Any], +) -> None: + """Persist the verified ownership receipt BEFORE allowing any local unlink.""" + provider.retained_source(receipt) + project = store.get(project_id) + local = {f["logical_path"]: (f["byte_length"], f["sha256"]) for f in project["source"]["files"]} + if project["source"]["kind"] != receipt["input"]["kind"] or local != receipt_files(receipt): + raise GaussianPipelineIntegrityError("Worker did not retain every imported source file") + store.update_source_storage( + project_id, + storage={ + "provider_endpoint": provider.endpoint, + "receipt": receipt, + "local_state": "verified", + }, + ) + + +def retire_local_source( + store: SimulationProjectStore, project_id: str, provider: GaussianPipelineGateway +) -> int: + """Exact-file deletion only; partial retirement can resume after a crash.""" + project = store.get(project_id) + source = project["source"] + storage = source.get("storage") or {} + if storage.get("local_state") == "remote": + provider.retained_source(storage["receipt"]) + return 0 + receipt = provider.retained_source(storage["receipt"], verify=True) + expected = receipt_files(receipt) + local_files = {f["logical_path"]: (f["byte_length"], f["sha256"]) for f in source["files"]} + if expected != local_files: + raise GaussianPipelineIntegrityError("Source receipt differs from local project") + root = store.source_root(project_id) + if root.is_symlink(): + raise GaussianPipelineIntegrityError("Source root is a symlink") + # Older Core releases could evict a complete archive for artifact capacity. + # Recover its ownership from fresh Worker hashes; no local bytes are deleted. + legacy_remote_archive = source["kind"] == "archive" and all( + not (root / name).exists() for name in expected + ) + paths = [] + fingerprints = {} + for name, (size, digest) in expected.items(): + candidate = root / name + if candidate.is_symlink() or not candidate.resolve().is_relative_to(root.resolve()): + raise GaussianPipelineIntegrityError("Local source path is unsafe") + if not candidate.exists(): + if ( + not legacy_remote_archive + and storage.get("local_state") not in {"retiring", "remote"} + ): + raise GaussianPipelineIntegrityError("Original disappeared before retirement") + continue + stat = candidate.stat() + if ( + not candidate.is_file() + or candidate.stat().st_size != size + or _digest(candidate) != digest + ): + raise GaussianPipelineIntegrityError("Local original changed; retirement refused") + fingerprints[candidate] = (stat.st_ino, stat.st_size, stat.st_mtime_ns) + paths.append(candidate) + for candidate in root.rglob("*"): + if candidate.is_symlink() or ( + candidate.is_file() and candidate.relative_to(root).as_posix() not in expected + ): + raise GaussianPipelineIntegrityError("Unregistered source file; retirement refused") + with store._lock: + current = store.get(project_id)["source"] + if ( + current["files"] != source["files"] + or current.get("storage", {}).get("receipt", {}).get("input") != receipt["input"] + ): + raise GaussianPipelineIntegrityError("Source ownership changed during verification") + if current["storage"].get("local_state") == "remote": + return 0 + for candidate in paths: + stat = candidate.lstat() + if ( + candidate.is_symlink() + or (stat.st_ino, stat.st_size, stat.st_mtime_ns) != fingerprints[candidate] + ): + raise GaussianPipelineIntegrityError("Source changed after verification") + # The analysis contract already permits only one small trajectory JSON. + # Retain this metadata, not another copy of the cloud/archive. + trajectories = [p for p in paths if p.name.lower() == "poses.json"] + if len(trajectories) == 1 and trajectories[0].stat().st_size <= 16 * 1024**2: + target = root.parent / "metadata" / "poses.json" + target.parent.mkdir(exist_ok=True) + with target.open("wb") as stream: + stream.write(trajectories[0].read_bytes()) + stream.flush() + os.fsync(stream.fileno()) + if os.name != "nt": + directory_fd = os.open(target.parent, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + storage = {**storage, "local_state": "retiring"} + store.update_source_storage(project_id, storage=storage) + removed = 0 + for candidate in paths: + removed += candidate.stat().st_size + candidate.unlink() + directories = sorted( + (p for p in root.rglob("*") if p.is_dir()), key=lambda p: len(p.parts), reverse=True + ) + for directory in directories: + directory.rmdir() + store.update_source_storage(project_id, storage={**storage, "local_state": "remote"}) + return removed + + +def prepare_source( + store: SimulationProjectStore, project_id: str, provider: GaussianPipelineGateway +) -> GaussianSourceBundleUpload: + project = store.get(project_id) + storage = project["source"].get("storage") + if storage: + receipt = provider.retained_source(storage["receipt"]) + else: + provider.require_source_retention() + root = store.source_root(project_id) + if project["source"]["kind"] == "archive": + item = project["source"]["files"][0] + archive = provider.upload_source_archive(root / item["logical_path"]) + original = {"kind": "archive", "archive": archive.to_dict()} + else: + entrypoint, source_format = discover_gaussian_source_bundle(root) + bundle = provider.upload_source_bundle( + root, + entrypoint=entrypoint, + source_format=source_format, + additional_paths=[f["logical_path"] for f in project["source"]["files"]], + ) + original = {"kind": "folder", "source": bundle.to_dict()} + receipt = provider.retain_source(original) + confirm_storage(store, project_id, provider, receipt) + retire_local_source(store, project_id, provider) + original = receipt["input"] + if original["kind"] == "folder": + return _source_bundle_upload(original["source"]) + prepared = store.get(project_id)["source"].get("prepared_receipt") + if prepared: + return _source_bundle_upload(provider.retained_source(prepared)["input"]["source"]) + bundle = provider.normalize_archive(GaussianArchiveUpload(**original["archive"])) + prepared = provider.retain_source({"kind": "folder", "source": bundle.to_dict()}) + store.update_source_storage(project_id, prepared_receipt=prepared) + return bundle + + +def _digest(path: Path) -> str: + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() diff --git a/src/k1link/web/infrastructure_api.py b/src/k1link/web/infrastructure_api.py index deea8c07..507c4ac7 100644 --- a/src/k1link/web/infrastructure_api.py +++ b/src/k1link/web/infrastructure_api.py @@ -3,11 +3,12 @@ import json from fastapi import APIRouter, Header, HTTPException, Request -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, StreamingResponse from pydantic import BaseModel, ConfigDict from k1link.simulation.ai_polygon.infrastructure_jobs import provider_identity from k1link.simulation.ai_polygon.urban_maps import validate_map +from k1link.simulation.gaussian_pipeline_gateway import configured_gaussian_pipeline_gateway class AnalysisRequest(BaseModel): @@ -59,6 +60,25 @@ def build_infrastructure_router(jobs, maps, worlds, runs, invoke, authenticate): world = invoke(worlds.get, world_id) if world.get("storage", {}).get("kind") != "project": raise HTTPException(400, "Для анализа нужен исходный Gaussian-проект.") + receipt = invoke(worlds.projects.remote_analysis_archive, world) + if receipt is not None: + provider = configured_gaussian_pipeline_gateway() + if provider is None: + raise HTTPException(503, "Исходник хранится на Worker. Подключите Worker.") + try: + provider.retained_source(receipt) + except Exception: + provider.close() + raise + def chunks(): + try: + yield from provider.stream_retained_archive(receipt) + finally: + provider.close() + return StreamingResponse(chunks(), media_type="application/octet-stream", headers={ + "ETag": '"' + receipt["input"]["archive"]["sha256"] + '"', + "Content-Length": str(receipt["input"]["archive"]["byte_length"]), + }) path, descriptor = invoke(worlds.projects.analysis_archive, world) return FileResponse( path, diff --git a/src/k1link/web/simulation_projects_api.py b/src/k1link/web/simulation_projects_api.py index ecfe239a..feee830a 100644 --- a/src/k1link/web/simulation_projects_api.py +++ b/src/k1link/web/simulation_projects_api.py @@ -116,6 +116,11 @@ class SimulationProjectDocument(BaseModel): updated_at_utc: str +class SimulationSourceRetention(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + receipt: dict[str, Any] + + class SimulationProjectPage(BaseModel): model_config = ConfigDict(extra="forbid", frozen=True) @@ -138,6 +143,10 @@ def build_simulation_projects_router( @router.post("/projects", response_model=SimulationProjectDocument, status_code=201) def create_project(request: SimulationProjectCreate) -> dict[str, Any]: + try: + service.require_import_worker() + except GaussianPipelineGatewayError as exc: + raise HTTPException(status_code=503, detail=f"Загрузка недоступна: {exc}") from exc try: return store.create( name=request.name, @@ -148,6 +157,17 @@ def build_simulation_projects_router( except SimulationProjectError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc + @router.post("/projects/{project_id}/source/retain", response_model=SimulationProjectDocument) + def retain_originals( + project_id: str, request: SimulationSourceRetention | None = None + ) -> dict[str, Any]: + try: + return service.retain_originals(project_id, request.receipt if request else None) + except GaussianPipelineGatewayError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + except SimulationProjectError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + @router.get("/projects/{project_id}", response_model=SimulationProjectDocument) def get_project(project_id: str) -> dict[str, Any]: try: diff --git a/tests/test_gaussian_pipeline_gateway.py b/tests/test_gaussian_pipeline_gateway.py index f1850e74..e2acfa77 100644 --- a/tests/test_gaussian_pipeline_gateway.py +++ b/tests/test_gaussian_pipeline_gateway.py @@ -489,3 +489,29 @@ def test_gateway_rejects_capabilities_without_runtime_provenance(tmp_path: Path) pytest.raises(GaussianPipelineGatewayError, match="provenance is unavailable"), ): gateway.capabilities() + + +def test_durable_archive_receipt_and_stream_do_not_use_local_staging(tmp_path): + raw = b"retained original archive" + original = {"kind": "archive", "archive": { + "upload_id": "archive-test", "archive_name": "scene.zip", "format": "zip", + "sha256": hashlib.sha256(raw).hexdigest(), "byte_length": len(raw), + }} + receipt = {"schema_version": "gaussian-pipeline.source-receipt/v1", + "source_id": "src-" + "a" * 64, "retention": "independent-of-jobs", + "verified_at_utc": "2026-11-07T00:00:00Z", "input": original} + seen = [] + def handler(request): + seen.append(str(request.url)) + if request.url.path.endswith("/archive"): + return httpx.Response(200, content=raw) + if request.method == "POST": + assert json.loads(request.content) == original + return httpx.Response(200, json=receipt) + with GaussianPipelineGateway("http://gaussian.test", _token_file(tmp_path), + transport=httpx.MockTransport(handler)) as gateway: + assert gateway.retain_source(original) == receipt + assert gateway.retained_source(receipt, verify=True) == receipt + assert b"".join(gateway.stream_retained_archive(receipt)) == raw + assert any(url.endswith("?verify=sha256") for url in seen) + assert sorted(p.name for p in tmp_path.iterdir()) == ["gaussian.token"] diff --git a/tests/test_simulation_projects.py b/tests/test_simulation_projects.py index a9be5a47..bead49ee 100644 --- a/tests/test_simulation_projects.py +++ b/tests/test_simulation_projects.py @@ -1,5 +1,7 @@ from __future__ import annotations +import copy +import hashlib import json from pathlib import Path from threading import Event @@ -14,6 +16,7 @@ from k1link.simulation.gaussian_pipeline_gateway import ( GaussianPipelineUnavailableError, GaussianSourceBundleUpload, GaussianSourceMemberUpload, + _bundle_sha256, ) from k1link.simulation.projects import ( SimulationProjectConflictError, @@ -157,6 +160,22 @@ def test_store_preserves_provider_job_and_stage_timing(tmp_path: Path) -> None: class _ReadyProvider: + endpoint = "http://worker.test:18090" + + def require_source_retention(self): + pass + + def retain_source(self, original): + return {"schema_version": "gaussian-pipeline.source-receipt/v1", + "source_id": "src-" + "a" * 64, "retention": "independent-of-jobs", + "verified_at_utc": "2026-11-07T00:00:00Z", "input": copy.deepcopy(original)} + + def job_original_source(self, job_id): + return {"kind": "folder", "source": self.get_job(job_id)["request"]["source"]} + + def retained_source(self, receipt, *, verify=False): + return copy.deepcopy(receipt) + def __init__(self, *, source_mesh: bool = False) -> None: self.deleted: list[str] = [] self.upload_calls = 0 @@ -173,28 +192,19 @@ class _ReadyProvider: *, entrypoint: str, source_format: str, + additional_paths: list[str] | None = None, ) -> GaussianSourceBundleUpload: self.upload_calls += 1 - members = [ - GaussianSourceMemberUpload("upload-1", entrypoint, "a" * 64, 23), - GaussianSourceMemberUpload("upload-2", "export/data.bin", "b" * 64, 4), - GaussianSourceMemberUpload("upload-3", "export/index.bin", "c" * 64, 5), - ] - if self.source_mesh: - members.append( - GaussianSourceMemberUpload( - "upload-4", - "export/Mesh_Files/scene.ply", - "e" * 64, - 3, - ) - ) + members = tuple( + GaussianSourceMemberUpload(f"upload-{index}", name, + hashlib.sha256((_root / name).read_bytes()).hexdigest(), + (_root / name).stat().st_size) + for index, name in enumerate(sorted(additional_paths or [])) + ) return GaussianSourceBundleUpload( - format=source_format, - entrypoint=entrypoint, - bundle_sha256="d" * 64, - total_byte_length=sum(member.byte_length for member in members), - members=tuple(members), + format=source_format, entrypoint=entrypoint, + bundle_sha256=_bundle_sha256(source_format, entrypoint, members), + total_byte_length=sum(member.byte_length for member in members), members=members, ) def submit_build(self, document: dict[str, object]) -> dict[str, object]: @@ -611,7 +621,7 @@ def test_failed_project_retries_from_retained_source_and_releases_old_job(tmp_pa assert queued["source"]["uploaded_byte_length"] == queued["source"]["total_byte_length"] -def test_import_evicts_only_worker_backed_archive_staging_when_disk_is_low( +def test_low_disk_never_evicts_archive_without_durable_receipt( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -657,13 +667,12 @@ def test_import_evicts_only_worker_backed_archive_staging_when_disk_is_low( } ] - service._ensure_import_capacity( - project["project_id"], - artifacts, - store.artifacts_root(project["project_id"]), - ) + with pytest.raises(RuntimeError, match="Недостаточно места"): + service._ensure_import_capacity( + project["project_id"], artifacts, store.artifacts_root(project["project_id"]), + ) - assert not source_path.exists() + assert source_path.exists() retained_metadata = store.get(project["project_id"])["source"] assert retained_metadata["uploaded_byte_length"] == retained_metadata["total_byte_length"] @@ -791,7 +800,7 @@ def test_ready_project_rebuilds_from_retained_source_and_preserves_viewer_settin def test_api_exposes_same_origin_resumable_upload_contract(tmp_path: Path) -> None: store = SimulationProjectStore(tmp_path) - service = SimulationProjectService(store, provider_factory=lambda: None) + service = SimulationProjectService(store, provider_factory=_ReadyProvider) app = FastAPI() app.include_router(build_simulation_projects_router(store=store, service=service)) client = TestClient(app) @@ -919,3 +928,201 @@ def test_catalog_adds_default_ugv_preset_to_v2_viewer_settings(tmp_path: Path) - "camera": {"invert_horizontal": False, "invert_vertical": True}, "ugv": _default_ugv_settings(), } + + +def _retention_fixture(tmp_path): + store = SimulationProjectStore(tmp_path) + project = store.create(name="Retained", scene_type="outdoor", source_kind="folder", + files=_folder_files()) + _upload_all(store, project) + store.begin_build(project["project_id"]) + return store, project["project_id"], _ReadyProvider() + + +def test_worker_unavailable_refuses_import_before_local_allocation(tmp_path): + store = SimulationProjectStore(tmp_path) + service = SimulationProjectService(store, provider_factory=lambda: None) + app = FastAPI() + app.include_router(build_simulation_projects_router(store=store, service=service)) + response = TestClient(app).post("/api/v1/simulation-worlds/projects", json={ + "schema_version": "missioncore.simulation-project-create/v1", "name": "No worker", + "scene_type": "outdoor", "source_kind": "folder", "files": _folder_files(), + }) + assert response.status_code == 503 + assert store.list() == [] + + +def test_original_eviction_rebuild_and_provider_address_change(tmp_path): + from k1link.simulation.source_retention import prepare_source + store, project_id, provider = _retention_fixture(tmp_path) + original = prepare_source(store, project_id, provider) + assert not list(store.source_root(project_id).rglob("*.bin")) + assert store.get(project_id)["source"]["storage"]["local_state"] == "remote" + # Relocated service with the same persistent volume and receipt needs no reupload. + provider.endpoint = "http://replacement-host:18090" + again = prepare_source(store, project_id, provider) + assert again == original + assert provider.upload_calls == 1 + + +def test_wrong_or_incomplete_worker_receipt_never_removes_local_files(tmp_path): + from k1link.simulation.source_retention import prepare_source + store, project_id, provider = _retention_fixture(tmp_path) + original = provider.retain_source + def wrong_receipt(value): + receipt = original(value) + receipt["input"]["source"]["members"][0]["sha256"] = "0" * 64 + return receipt + provider.retain_source = wrong_receipt + with pytest.raises(RuntimeError): + prepare_source(store, project_id, provider) + assert len(list(store.source_root(project_id).rglob("*.*"))) == 3 + assert "storage" not in store.get(project_id)["source"] + + +def test_changed_local_original_is_never_evicted(tmp_path): + from k1link.simulation.source_retention import confirm_storage, retire_local_source + store, project_id, provider = _retention_fixture(tmp_path) + files = store.get(project_id)["source"]["files"] + bundle = provider.upload_source_bundle( + store.source_root(project_id), entrypoint="export/scene.lcc", + source_format="lcc", additional_paths=[f["logical_path"] for f in files]) + receipt = provider.retain_source({"kind": "folder", "source": bundle.to_dict()}) + confirm_storage(store, project_id, provider, receipt) + target = store.source_root(project_id) / "export/data.bin" + target.write_bytes(b"evil") + with pytest.raises(RuntimeError, match="changed"): + retire_local_source(store, project_id, provider) + assert target.read_bytes() == b"evil" + assert len(list(store.source_root(project_id).rglob("*.*"))) == 3 + + +def test_partial_retirement_resumes_from_persisted_receipt(tmp_path, monkeypatch): + from k1link.simulation.source_retention import prepare_source + store, project_id, provider = _retention_fixture(tmp_path) + unlink = Path.unlink + count = 0 + def interrupted(path, *args, **kwargs): + nonlocal count + if "source" in path.parts: + count += 1 + if count == 2: + raise OSError("power interrupted") + return unlink(path, *args, **kwargs) + with monkeypatch.context() as patch: + patch.setattr(Path, "unlink", interrupted) + with pytest.raises(OSError, match="power interrupted"): + prepare_source(store, project_id, provider) + assert store.get(project_id)["source"]["storage"]["local_state"] == "retiring" + restarted = SimulationProjectStore(tmp_path) + prepare_source(restarted, project_id, provider) + assert restarted.get(project_id)["source"]["storage"]["local_state"] == "remote" + assert provider.upload_calls == 1 + + +def test_archive_is_retained_before_normalization_failure(tmp_path): + from k1link.simulation.gaussian_pipeline_gateway import GaussianArchiveUpload + from k1link.simulation.source_retention import prepare_source + store = SimulationProjectStore(tmp_path) + project = store.create(name="Archive", scene_type="outdoor", source_kind="archive", + files=[{"logical_path": "scene.zip", "byte_length": 4}]) + store.append_upload(project["project_id"], project["source"]["files"][0]["file_id"], + offset=0, payload=b"test") + store.begin_build(project["project_id"]) + provider = _ReadyProvider() + provider.upload_source_archive = lambda path: GaussianArchiveUpload( + "archive-id", "scene.zip", "zip", hashlib.sha256(b"test").hexdigest(), 4) + def failed(_archive): + assert not (store.source_root(project["project_id"]) / "scene.zip").exists() + raise RuntimeError("unsupported archive") + provider.normalize_archive = failed + with pytest.raises(RuntimeError, match="unsupported archive"): + prepare_source(store, project["project_id"], provider) + saved = store.get(project["project_id"])["source"]["storage"]["receipt"] + assert saved["input"]["archive"]["sha256"] == hashlib.sha256(b"test").hexdigest() + + +def test_legacy_folder_migration_preserves_ready_scene(tmp_path): + store, project_id, provider = _retention_fixture(tmp_path) + files = store.get(project_id)["source"]["files"] + source = provider.upload_source_bundle(store.source_root(project_id), + entrypoint="export/scene.lcc", source_format="lcc", + additional_paths=[f["logical_path"] for f in files]) + store.update_processing(project_id, status="processing", + provider_job_id="gsp-20260826000000-deadbeef", + bundle_sha256=source.bundle_sha256) + result = provider.get_result("gsp-20260826000000-deadbeef") + store.complete(project_id, result=result, artifacts=result["artifacts"], + world_manifest=_world_manifest(project_id, result["artifacts"])) + before = store.get(project_id) + get_job = provider.get_job + provider.get_job = lambda job_id: {**get_job(job_id), "request": {"source": source.to_dict()}} + service = SimulationProjectService(store, provider_factory=lambda: provider) + after = service.retain_originals(project_id) + for key in ("status", "provider", "artifacts", "world_manifest", "viewer_settings"): + assert before[key] == after[key] + assert before["source"]["bundle_sha256"] == after["source"]["bundle_sha256"] + assert after["source"]["storage"]["local_state"] == "remote" + assert provider.deleted == [] + assert provider.submit_calls == 0 + + +def test_remote_hash_verification_does_not_block_catalog_reads(tmp_path): + from threading import Thread + + from k1link.simulation.source_retention import confirm_storage, retire_local_source + store, project_id, provider = _retention_fixture(tmp_path) + files = store.get(project_id)["source"]["files"] + bundle = provider.upload_source_bundle(store.source_root(project_id), + entrypoint="export/scene.lcc", source_format="lcc", + additional_paths=[f["logical_path"] for f in files]) + confirm_storage(store, project_id, provider, + provider.retain_source({"kind": "folder", "source": bundle.to_dict()})) + verifying, release, read_completed = Event(), Event(), Event() + previous = provider.retained_source + def slow(receipt, *, verify=False): + if verify: + verifying.set() + assert release.wait(2) + return previous(receipt) + provider.retained_source = slow + worker = Thread(target=retire_local_source, args=(store, project_id, provider)) + worker.start() + assert verifying.wait(1) + reader = Thread(target=lambda: (store.get(project_id), read_completed.set())) + reader.start() + try: + assert read_completed.wait(0.5), "remote hashing blocked the entire scene catalog" + finally: + release.set() + reader.join(2) + worker.join(2) + assert store.get(project_id)["source"]["storage"]["local_state"] == "remote" + + +def test_legacy_absent_archive_recovers_verified_remote_ownership(tmp_path): + from k1link.simulation.source_retention import confirm_storage, retire_local_source + + store = SimulationProjectStore(tmp_path) + project = store.create(name="Legacy archive", scene_type="outdoor", source_kind="archive", + files=[{"logical_path": "scene.zip", "byte_length": 4}]) + project_id = project["project_id"] + store.append_upload(project_id, project["source"]["files"][0]["file_id"], + offset=0, payload=b"test") + store.begin_build(project_id) + provider = _ReadyProvider() + receipt = provider.retain_source({"kind": "archive", "archive": { + "upload_id": "archive-id", "archive_name": "scene.zip", "format": "zip", + "sha256": hashlib.sha256(b"test").hexdigest(), "byte_length": 4, + }}) + (store.source_root(project_id) / "scene.zip").unlink() + confirm_storage(store, project_id, provider, receipt) + checks = [] + original = provider.retained_source + def verified(value, *, verify=False): + checks.append(verify) + return original(value) + provider.retained_source = verified + assert retire_local_source(store, project_id, provider) == 0 + assert checks == [True] + assert store.get(project_id)["source"]["storage"]["local_state"] == "remote"