Retain imported originals on Worker before retiring Core staging

This commit is contained in:
DCCONSTRUCTIONS
2026-11-07 16:45:17 +03:00
parent b0332fa377
commit 09c13a5c68
10 changed files with 710 additions and 78 deletions
@@ -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"])
@@ -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,
+63 -47
View File
@@ -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):
+227
View File
@@ -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()
+21 -1
View File
@@ -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,
+20
View File
@@ -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: