refactor(lab): move execution to Worker and manage replay and transfer lifecycles
This commit is contained in:
@@ -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"
|
||||
),
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 = ?")
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user