chore(storage): bound build retention, caches and test resources
Track build ownership, qualified pins and bounded cache/log lifecycles. Move Vite fixtures to a job-owned server helper and preserve private outputs outside Git.
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
"""Publication budgets for local derived caches; never evicts retained data.
|
||||
|
||||
Existing generations, unknown files and in-flight files all count. Budget
|
||||
exhaustion refuses a new disk copy; callers that can work without it may skip it.
|
||||
This is a publication quota, not a filesystem quota for renderer scratch output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
GiB = 1024**3
|
||||
MiB = 1024**2
|
||||
LIMITS = {
|
||||
"camera-frame-cache": 256 * MiB,
|
||||
"lidar-read-cache": 16 * MiB,
|
||||
"camera-media-index": 64 * MiB,
|
||||
"perception-overlays": GiB,
|
||||
"calibrated-fusion-overlays": GiB,
|
||||
"integrated-perception-overlays": 4 * GiB,
|
||||
"laboratory-rerun-overlays": 4 * GiB,
|
||||
"observatory-portable-replay-cache": 4 * GiB,
|
||||
"editor-cache": 4 * GiB,
|
||||
}
|
||||
FREE_RESERVE = 2 * GiB
|
||||
_LOCK = threading.RLock()
|
||||
_LOCK_NAME = ".publication-budget.lock"
|
||||
|
||||
|
||||
class CacheCapacityError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def usage(root: Path) -> tuple[int, int]:
|
||||
total = count = 0
|
||||
for base, directories, files in os.walk(root, followlinks=False):
|
||||
for name in directories + files:
|
||||
p = Path(base) / name
|
||||
s = p.lstat()
|
||||
if stat.S_ISDIR(s.st_mode):
|
||||
continue
|
||||
if not stat.S_ISREG(s.st_mode):
|
||||
raise CacheCapacityError("Cache contains an unsafe path; preserved")
|
||||
if p == root / _LOCK_NAME:
|
||||
continue
|
||||
total += s.st_size
|
||||
count += 1
|
||||
if count > 100000:
|
||||
raise CacheCapacityError("Cache inventory exceeds its file budget; preserved")
|
||||
return total, count
|
||||
|
||||
|
||||
@contextmanager
|
||||
def cache_publication(
|
||||
root: Path,
|
||||
additional_bytes: int,
|
||||
*,
|
||||
kind=None,
|
||||
limit=None,
|
||||
reserve=FREE_RESERVE,
|
||||
max_files=10000,
|
||||
error_type=CacheCapacityError,
|
||||
):
|
||||
"""Lock admission through publication. Count temporary bytes already on disk.
|
||||
|
||||
additional_bytes includes only bytes not yet in this root; a file renamed
|
||||
within it contributes zero additional bytes. Callers include sidecar overhead.
|
||||
Unknown legacy contents stay in place even if already above the new limit.
|
||||
"""
|
||||
root = root.expanduser().absolute()
|
||||
maximum = LIMITS[kind or root.name] if limit is None else limit
|
||||
if type(additional_bytes) is not int or additional_bytes < 0 or maximum < 1:
|
||||
raise ValueError("Invalid cache publication budget")
|
||||
ancestor = root
|
||||
while not ancestor.exists():
|
||||
ancestor = ancestor.parent
|
||||
if ancestor.resolve() != ancestor:
|
||||
raise CacheCapacityError("Cache ancestor is not canonical")
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if root.resolve() != root or not stat.S_ISDIR(root.lstat().st_mode):
|
||||
raise CacheCapacityError("Cache root is not canonical")
|
||||
with _LOCK:
|
||||
fd = os.open(root / _LOCK_NAME, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
s = os.fstat(fd)
|
||||
if not stat.S_ISREG(s.st_mode) or s.st_nlink != 1 or s.st_uid != os.getuid():
|
||||
raise CacheCapacityError("Unsafe cache publication lock")
|
||||
# Operator cache publication is Mac/Linux owned, never the remote Worker.
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
current, count = usage(root)
|
||||
if current + additional_bytes > maximum or count >= max_files:
|
||||
raise CacheCapacityError("Достигнут лимит кэша. Сохранённые данные не удалены.")
|
||||
if shutil.disk_usage(root).free < additional_bytes + reserve:
|
||||
raise CacheCapacityError("Недостаточно свободного места для новой копии кэша.")
|
||||
yield
|
||||
except CacheCapacityError as exc:
|
||||
if error_type is CacheCapacityError:
|
||||
raise
|
||||
raise error_type(str(exc)) from exc
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def require_cache_room(root: Path, additional_bytes=0, **kwargs):
|
||||
with cache_publication(root, additional_bytes, **kwargs):
|
||||
pass
|
||||
@@ -18,6 +18,7 @@ import rerun as rr
|
||||
from rerun.components import FillMode
|
||||
|
||||
from k1link.artifacts import write_json_atomic
|
||||
from k1link.cache_budget import cache_publication, require_cache_room
|
||||
from k1link.sessions import SessionIntegrityError
|
||||
|
||||
from .jobs import CameraComputeJob, validate_camera_compute_job
|
||||
@@ -104,31 +105,43 @@ class RecordedCalibratedFusionStore:
|
||||
cached = _read_cache(output, sidecar, fusion, recording_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
require_cache_room(
|
||||
self.cache_root,
|
||||
65536,
|
||||
kind="calibrated-fusion-overlays",
|
||||
error_type=RecordedPerceptionOverlayError,
|
||||
)
|
||||
payload = _render_fusion(
|
||||
fusion,
|
||||
application_id=application_id,
|
||||
recording_id=recording_id,
|
||||
)
|
||||
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
with temporary.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.calibrated-fusion-overlay-cache/v1",
|
||||
"fusion_id": fusion.fusion_id,
|
||||
"recording_id": recording_id,
|
||||
"byte_length": len(payload),
|
||||
"sha256": hashlib.sha256(payload).hexdigest(),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
with cache_publication(
|
||||
self.cache_root,
|
||||
len(payload) + 65536,
|
||||
kind="calibrated-fusion-overlays",
|
||||
error_type=RecordedPerceptionOverlayError,
|
||||
):
|
||||
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
with temporary.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.calibrated-fusion-overlay-cache/v1",
|
||||
"fusion_id": fusion.fusion_id,
|
||||
"recording_id": recording_id,
|
||||
"byte_length": len(payload),
|
||||
"sha256": hashlib.sha256(payload).hexdigest(),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return payload
|
||||
|
||||
def _latest(self, session_id: str) -> RecordedCalibratedFusion | None:
|
||||
@@ -540,9 +553,8 @@ def _read_labels(path: Path) -> list[str]:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise SessionIntegrityError("calibrated fusion labels are unavailable") from exc
|
||||
if (
|
||||
not isinstance(value, list)
|
||||
or any(not isinstance(item, str) or not 1 <= len(item) <= 256 for item in value)
|
||||
if not isinstance(value, list) or any(
|
||||
not isinstance(item, str) or not 1 <= len(item) <= 256 for item in value
|
||||
):
|
||||
raise SessionIntegrityError("calibrated fusion labels are invalid")
|
||||
return value
|
||||
|
||||
@@ -28,6 +28,7 @@ from k1link.artifact_gateway import (
|
||||
ArtifactStoreUnavailable,
|
||||
)
|
||||
from k1link.artifacts import write_json_atomic
|
||||
from k1link.cache_budget import CacheCapacityError, cache_publication, require_cache_room
|
||||
from k1link.sessions import SessionIntegrityError
|
||||
|
||||
from .jobs import CameraComputeJob, validate_camera_compute_job
|
||||
@@ -498,6 +499,12 @@ class IntegratedPerceptionOverlayStore:
|
||||
)
|
||||
return cached
|
||||
self._set_status(key, state="preparing", phase="rendering")
|
||||
require_cache_room(
|
||||
self.cache_root,
|
||||
65536,
|
||||
kind="integrated-perception-overlays",
|
||||
error_type=RecordedPerceptionOverlayError,
|
||||
)
|
||||
payload = _render(
|
||||
result,
|
||||
application_id=application_id,
|
||||
@@ -506,29 +513,35 @@ class IntegratedPerceptionOverlayStore:
|
||||
temporary_root=cache,
|
||||
)
|
||||
self._set_status(key, state="preparing", phase="cache-write")
|
||||
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
with temporary.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": OVERLAY_CACHE_SCHEMA,
|
||||
"renderer_version": OVERLAY_RENDERER_VERSION,
|
||||
"session_id": session_id,
|
||||
"result_id": result.result_id,
|
||||
"result_created_at_utc": result.created_at_utc,
|
||||
"recording_id": recording_id,
|
||||
"byte_length": len(payload),
|
||||
"sha256": hashlib.sha256(payload).hexdigest(),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
with cache_publication(
|
||||
self.cache_root,
|
||||
len(payload) + 65536,
|
||||
kind="integrated-perception-overlays",
|
||||
error_type=RecordedPerceptionOverlayError,
|
||||
):
|
||||
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
with temporary.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": OVERLAY_CACHE_SCHEMA,
|
||||
"renderer_version": OVERLAY_RENDERER_VERSION,
|
||||
"session_id": session_id,
|
||||
"result_id": result.result_id,
|
||||
"result_created_at_utc": result.created_at_utc,
|
||||
"recording_id": recording_id,
|
||||
"byte_length": len(payload),
|
||||
"sha256": hashlib.sha256(payload).hexdigest(),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
self._set_status(
|
||||
key,
|
||||
state="ready",
|
||||
@@ -770,9 +783,7 @@ class IntegratedPerceptionOverlayStore:
|
||||
or descriptor.result_id != result.result_id
|
||||
or descriptor.created_at_utc != result.created_at_utc
|
||||
):
|
||||
raise RecordedPerceptionOverlayError(
|
||||
"integrated perception admission identity changed"
|
||||
)
|
||||
raise RecordedPerceptionOverlayError("integrated perception admission identity changed")
|
||||
cache_root = _private_directory(self.cache_root)
|
||||
session_cache = _private_child(cache_root, descriptor.session_id)
|
||||
self._write_admission_document(
|
||||
@@ -790,17 +801,24 @@ class IntegratedPerceptionOverlayStore:
|
||||
session_cache: Path,
|
||||
admission: _OverlayAdmission,
|
||||
) -> None:
|
||||
write_json_atomic(
|
||||
session_cache / "admission.json",
|
||||
{
|
||||
"schema_version": OVERLAY_ADMISSION_SCHEMA,
|
||||
"renderer_version": OVERLAY_RENDERER_VERSION,
|
||||
"session_id": admission.session_id,
|
||||
"result_id": admission.result_id,
|
||||
"result_json_sha256": admission.result_json_sha256,
|
||||
"result_created_at_utc": admission.result_created_at_utc,
|
||||
},
|
||||
)
|
||||
try:
|
||||
with cache_publication(
|
||||
session_cache.parent, 65536, kind="integrated-perception-overlays"
|
||||
):
|
||||
write_json_atomic(
|
||||
session_cache / "admission.json",
|
||||
{
|
||||
"schema_version": OVERLAY_ADMISSION_SCHEMA,
|
||||
"renderer_version": OVERLAY_RENDERER_VERSION,
|
||||
"session_id": admission.session_id,
|
||||
"result_id": admission.result_id,
|
||||
"result_json_sha256": admission.result_json_sha256,
|
||||
"result_created_at_utc": admission.result_created_at_utc,
|
||||
},
|
||||
)
|
||||
except CacheCapacityError:
|
||||
# A full disk cache must not prevent recovery of an already sealed overlay.
|
||||
pass
|
||||
|
||||
def _latest_descriptor(self, session_id: str) -> _ResultDescriptor | None:
|
||||
try:
|
||||
@@ -1274,8 +1292,7 @@ def _read_result_descriptor(result_root: Path) -> _ResultDescriptor:
|
||||
or root.name != f"e10-integrated-perception-{identity_sha256}"
|
||||
or hashlib.sha256(_canonical_json(identity)).hexdigest() != identity_sha256
|
||||
or result.get("acceptance_state") != "accepted"
|
||||
or result.get("publication_scope")
|
||||
!= "recorded-integrated-realtime-qualification-only"
|
||||
or result.get("publication_scope") != "recorded-integrated-realtime-qualification-only"
|
||||
or not isinstance(session_id, str)
|
||||
or _SAFE_RECORDING_ID.fullmatch(session_id) is None
|
||||
or not isinstance(job_id, str)
|
||||
|
||||
@@ -16,6 +16,7 @@ import numpy as np
|
||||
import rerun as rr
|
||||
|
||||
from k1link.artifacts import write_json_atomic
|
||||
from k1link.cache_budget import cache_publication, require_cache_room
|
||||
from k1link.sessions import SessionIntegrityError
|
||||
|
||||
from .jobs import CameraComputeJob, validate_camera_compute_job
|
||||
@@ -222,6 +223,12 @@ class RecordedPerceptionOverlayStore:
|
||||
cached = _read_cached_overlay(output, sidecar, result)
|
||||
if cached is not None:
|
||||
return cached
|
||||
require_cache_room(
|
||||
self.cache_root,
|
||||
65536,
|
||||
kind="perception-overlays",
|
||||
error_type=RecordedPerceptionOverlayError,
|
||||
)
|
||||
payload = _render_overlay(
|
||||
result,
|
||||
application_id=application_id,
|
||||
@@ -229,26 +236,32 @@ class RecordedPerceptionOverlayStore:
|
||||
ffmpeg_path=self.ffmpeg_path,
|
||||
ffprobe_path=self.ffprobe_path,
|
||||
)
|
||||
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
with temporary.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.perception-overlay-cache/v1",
|
||||
"result_id": result.result_id,
|
||||
"recording_id": recording_id,
|
||||
"byte_length": len(payload),
|
||||
"sha256": hashlib.sha256(payload).hexdigest(),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
with cache_publication(
|
||||
self.cache_root,
|
||||
len(payload) + 65536,
|
||||
kind="perception-overlays",
|
||||
error_type=RecordedPerceptionOverlayError,
|
||||
):
|
||||
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
with temporary.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.perception-overlay-cache/v1",
|
||||
"result_id": result.result_id,
|
||||
"recording_id": recording_id,
|
||||
"byte_length": len(payload),
|
||||
"sha256": hashlib.sha256(payload).hexdigest(),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return payload
|
||||
|
||||
def _latest_result(self, session_id: str) -> RecordedPerceptionResult | None:
|
||||
@@ -408,10 +421,7 @@ def _render_overlay(
|
||||
f"{detection.class_name} · {detection.score:.0%}"
|
||||
for detection in frame.detections
|
||||
],
|
||||
colors=[
|
||||
_class_color(detection.class_id)
|
||||
for detection in frame.detections
|
||||
],
|
||||
colors=[_class_color(detection.class_id) for detection in frame.detections],
|
||||
show_labels=True,
|
||||
),
|
||||
)
|
||||
@@ -431,16 +441,9 @@ def _render_overlay(
|
||||
|
||||
|
||||
def _camera_source_bytes(job: CameraComputeJob) -> bytes:
|
||||
epoch = (
|
||||
job.job_root
|
||||
/ "input"
|
||||
/ "camera"
|
||||
/ job.source_id
|
||||
/ f"epoch-{job.codec_epoch}"
|
||||
)
|
||||
epoch = job.job_root / "input" / "camera" / job.source_id / f"epoch-{job.codec_epoch}"
|
||||
paths = [epoch / "init.mp4"] + [
|
||||
epoch / "segments" / f"{sequence}.m4s"
|
||||
for sequence in range(1, job.segment_count + 1)
|
||||
epoch / "segments" / f"{sequence}.m4s" for sequence in range(1, job.segment_count + 1)
|
||||
]
|
||||
total = sum(path.stat().st_size for path in paths)
|
||||
if total > MAX_OVERLAY_SOURCE_BYTES:
|
||||
|
||||
@@ -32,6 +32,8 @@ import rerun as rr
|
||||
import rerun_bindings as bindings
|
||||
from PIL import Image
|
||||
|
||||
from k1link.cache_budget import cache_publication, require_cache_room
|
||||
|
||||
APPLICATION_ID: Final = "nodedc_mission_core_recorded"
|
||||
SESSION_TIMELINE: Final = "session_time"
|
||||
RENDERER_VERSION: Final = "upstream-rerun-0.36.3-encoded-optimized-v6"
|
||||
@@ -223,6 +225,12 @@ def canonical_lab_overlay(
|
||||
_memory_cache[key] = restored
|
||||
return restored
|
||||
|
||||
require_cache_room(
|
||||
cache,
|
||||
MAX_OVERLAY_BYTES,
|
||||
kind="laboratory-rerun-overlays",
|
||||
error_type=CanonicalLabOverlayError,
|
||||
)
|
||||
temporary = cache / f".{identity}.{uuid4().hex}.rrd"
|
||||
proxy: Path | None = None
|
||||
source: Path | None = None
|
||||
@@ -237,20 +245,23 @@ def canonical_lab_overlay(
|
||||
raise CanonicalLabOverlayError("canonical LAB overlay size is invalid")
|
||||
digest = _sha256(temporary)
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
_write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.canonical-lab-rerun-overlay/v1",
|
||||
"renderer_version": RENDERER_VERSION,
|
||||
"result_id": result_id,
|
||||
"result_sha256": result_sha256,
|
||||
"recording_id": recording_id,
|
||||
"base_generation_sha256": base_generation_sha256,
|
||||
"byte_length": stat.st_size,
|
||||
"sha256": digest,
|
||||
},
|
||||
)
|
||||
with cache_publication(
|
||||
cache, 65536, kind="laboratory-rerun-overlays", error_type=CanonicalLabOverlayError
|
||||
):
|
||||
os.replace(temporary, output)
|
||||
_write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.canonical-lab-rerun-overlay/v1",
|
||||
"renderer_version": RENDERER_VERSION,
|
||||
"result_id": result_id,
|
||||
"result_sha256": result_sha256,
|
||||
"recording_id": recording_id,
|
||||
"base_generation_sha256": base_generation_sha256,
|
||||
"byte_length": stat.st_size,
|
||||
"sha256": digest,
|
||||
},
|
||||
)
|
||||
artifact = CanonicalLabOverlayArtifact(output, stat.st_size, digest)
|
||||
_memory_cache[key] = artifact
|
||||
return artifact
|
||||
@@ -327,6 +338,12 @@ def canonical_lab_replay(
|
||||
_replay_memory_cache[key] = restored
|
||||
return restored
|
||||
|
||||
require_cache_room(
|
||||
cache,
|
||||
MAX_REPLAY_BYTES,
|
||||
kind="laboratory-rerun-overlays",
|
||||
error_type=CanonicalLabOverlayError,
|
||||
)
|
||||
temporary = cache / f".{identity}.{uuid4().hex}.replay.rrd"
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
@@ -371,20 +388,23 @@ def canonical_lab_replay(
|
||||
stat = temporary.stat()
|
||||
digest = _sha256(temporary)
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, output)
|
||||
_write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.canonical-lab-rerun-replay/v1",
|
||||
"renderer_version": REPLAY_RENDERER_VERSION,
|
||||
"result_id": result_id,
|
||||
"recording_id": recording_id,
|
||||
"base_generation_sha256": base_generation_sha256,
|
||||
"overlay_sha256": overlay.sha256,
|
||||
"byte_length": stat.st_size,
|
||||
"sha256": digest,
|
||||
},
|
||||
)
|
||||
with cache_publication(
|
||||
cache, 65536, kind="laboratory-rerun-overlays", error_type=CanonicalLabOverlayError
|
||||
):
|
||||
os.replace(temporary, output)
|
||||
_write_json_atomic(
|
||||
sidecar,
|
||||
{
|
||||
"schema_version": "missioncore.canonical-lab-rerun-replay/v1",
|
||||
"renderer_version": REPLAY_RENDERER_VERSION,
|
||||
"result_id": result_id,
|
||||
"recording_id": recording_id,
|
||||
"base_generation_sha256": base_generation_sha256,
|
||||
"overlay_sha256": overlay.sha256,
|
||||
"byte_length": stat.st_size,
|
||||
"sha256": digest,
|
||||
},
|
||||
)
|
||||
artifact = CanonicalLabReplayArtifact(output, stat.st_size, digest)
|
||||
_replay_memory_cache[key] = artifact
|
||||
return artifact
|
||||
|
||||
@@ -31,3 +31,61 @@ def prepare_launchd_log(path: Path) -> None:
|
||||
os.fchmod(descriptor, 0o600)
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def bounded_launchd_output(document: dict, repository: Path, *, uv_path=None) -> dict:
|
||||
"""Preserve a declared command behind a single bounded output owner.
|
||||
|
||||
uv is the accepted Mac privacy execution boundary for this checkout. Its
|
||||
bootstrap output is discarded; child output and tracebacks go to the owned
|
||||
journal. launchd still owns the full process group and the original policy.
|
||||
"""
|
||||
result = dict(document)
|
||||
arguments = list(result["ProgramArguments"])
|
||||
if "k1link.rotating_process" in arguments:
|
||||
service_command(result) # Validate the existing owner instead of nesting wrappers.
|
||||
result["StandardOutPath"] = result["StandardErrorPath"] = "/dev/null"
|
||||
return result
|
||||
journal = result.get("StandardErrorPath") or result.get("StandardOutPath")
|
||||
if not journal or journal == "/dev/null":
|
||||
raise ValueError("An explicit service journal is required")
|
||||
path = Path(journal)
|
||||
if not path.is_absolute() or path.suffix != ".log":
|
||||
raise ValueError("Invalid service journal")
|
||||
# Legacy output is kept intact. Fresh managed generations alone rotate.
|
||||
managed = path.with_name(path.stem + ".managed.log")
|
||||
result["ProgramArguments"] = [
|
||||
str(uv_path or "/opt/homebrew/bin/uv"),
|
||||
"run",
|
||||
"--no-sync",
|
||||
"--project",
|
||||
str(repository),
|
||||
"python",
|
||||
"-m",
|
||||
"k1link.rotating_process",
|
||||
"--log",
|
||||
str(managed),
|
||||
"--",
|
||||
*arguments,
|
||||
]
|
||||
result["StandardOutPath"] = result["StandardErrorPath"] = "/dev/null"
|
||||
return result
|
||||
|
||||
|
||||
def service_command(document: dict) -> list[str]:
|
||||
arguments = list(document["ProgramArguments"])
|
||||
if "k1link.rotating_process" in arguments:
|
||||
index = arguments.index("k1link.rotating_process")
|
||||
if arguments[index + 1 : index + 2] != ["--log"] or arguments[index + 3 : index + 4] != [
|
||||
"--"
|
||||
]:
|
||||
raise ValueError("Invalid managed journal command")
|
||||
return arguments[index + 4 :]
|
||||
return arguments
|
||||
|
||||
|
||||
def service_log_path(document: dict) -> Path:
|
||||
arguments = document["ProgramArguments"]
|
||||
if "k1link.rotating_process" in arguments:
|
||||
return Path(arguments[arguments.index("k1link.rotating_process") + 2])
|
||||
return Path(document["StandardErrorPath"])
|
||||
|
||||
@@ -10,19 +10,13 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final, cast
|
||||
|
||||
from k1link.launchd_logs import launchd_log_path
|
||||
from k1link.launchd_logs import bounded_launchd_output, launchd_log_path, service_log_path
|
||||
|
||||
MISSION_CORE_LAUNCH_AGENT_LABEL: Final = "com.nodedc.mission-core.local"
|
||||
MISSION_CORE_LAUNCH_AGENT_SCHEMA: Final = "missioncore.local-launch-agent-plan/v1"
|
||||
OBSERVATORY_LOCAL_WORKER_ENABLED_ENV: Final = (
|
||||
"MISSIONCORE_OBSERVATORY_WORKER_LOCAL_ENABLED"
|
||||
)
|
||||
OBSERVATORY_SOURCE_CAS_ROOT_ENV: Final = (
|
||||
"MISSIONCORE_OBSERVATORY_WORKER_SOURCE_CAS_ROOT"
|
||||
)
|
||||
OBSERVATORY_RESULT_STAGING_ROOT_ENV: Final = (
|
||||
"MISSIONCORE_OBSERVATORY_WORKER_RESULT_STAGING_ROOT"
|
||||
)
|
||||
OBSERVATORY_LOCAL_WORKER_ENABLED_ENV: Final = "MISSIONCORE_OBSERVATORY_WORKER_LOCAL_ENABLED"
|
||||
OBSERVATORY_SOURCE_CAS_ROOT_ENV: Final = "MISSIONCORE_OBSERVATORY_WORKER_SOURCE_CAS_ROOT"
|
||||
OBSERVATORY_RESULT_STAGING_ROOT_ENV: Final = "MISSIONCORE_OBSERVATORY_WORKER_RESULT_STAGING_ROOT"
|
||||
ARTIFACT_STORE_ROOT_ENV: Final = "MISSIONCORE_ARTIFACT_STORE_ROOT"
|
||||
|
||||
|
||||
@@ -62,7 +56,7 @@ class MissionCoreLaunchAgentPlan:
|
||||
"desired_program_arguments": list(self.desired_program_arguments),
|
||||
"current_process_type": self.current_process_type,
|
||||
"desired_process_type": "Interactive",
|
||||
"desired_log_path": plistlib.loads(self.desired_payload)["StandardOutPath"],
|
||||
"desired_log_path": str(service_log_path(plistlib.loads(self.desired_payload))),
|
||||
"changes": {
|
||||
"repository_migration": self.current_working_directory
|
||||
!= self.desired_working_directory,
|
||||
@@ -72,16 +66,13 @@ class MissionCoreLaunchAgentPlan:
|
||||
if self.preserved_data_directory is not None
|
||||
else None
|
||||
),
|
||||
"dependency_sync_disabled": "--no-sync"
|
||||
in self.desired_program_arguments,
|
||||
"dependency_sync_disabled": "--no-sync" in self.desired_program_arguments,
|
||||
"self_health_watchdog": True,
|
||||
"bounded_launchd_exit_timeout_seconds": 20,
|
||||
"keep_alive": True,
|
||||
"process_group_owned": True,
|
||||
"operator_interactive_resources": True,
|
||||
"local_observatory_worker_enabled": (
|
||||
self.local_observatory_worker_enabled
|
||||
),
|
||||
"local_observatory_worker_enabled": (self.local_observatory_worker_enabled),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -113,9 +104,8 @@ def plan_mission_core_launch_agent(
|
||||
raise MissionCoreLaunchAgentError("current launch agent working directory is invalid")
|
||||
if expected_current_repository is None and current_working_directory != str(repository):
|
||||
raise MissionCoreLaunchAgentError("current launch agent targets another repository")
|
||||
if (
|
||||
expected_current_repository is not None
|
||||
and current_working_directory != str(expected_current_repository)
|
||||
if expected_current_repository is not None and current_working_directory != str(
|
||||
expected_current_repository
|
||||
):
|
||||
raise MissionCoreLaunchAgentError(
|
||||
"current launch agent does not target the expected current repository"
|
||||
@@ -133,11 +123,7 @@ def plan_mission_core_launch_agent(
|
||||
# accepted local execution boundary. ``--no-sync`` keeps launch startup
|
||||
# deterministic and prevents dependency mutation during recovery.
|
||||
uv_entrypoint = Path(current_arguments[0])
|
||||
if (
|
||||
not uv_entrypoint.is_absolute()
|
||||
or uv_entrypoint.name != "uv"
|
||||
or not uv_entrypoint.exists()
|
||||
):
|
||||
if not uv_entrypoint.is_absolute() or uv_entrypoint.name != "uv" or not uv_entrypoint.exists():
|
||||
raise MissionCoreLaunchAgentError("Mission Core uv entrypoint is unavailable")
|
||||
current_repository = Path(current_working_directory)
|
||||
repository_migration = current_repository != repository
|
||||
@@ -201,6 +187,8 @@ def plan_mission_core_launch_agent(
|
||||
"StandardOutPath": str(log_path),
|
||||
"StandardErrorPath": str(log_path),
|
||||
}
|
||||
desired = bounded_launchd_output(desired, repository, uv_path=uv_entrypoint)
|
||||
desired_program_arguments = tuple(desired["ProgramArguments"])
|
||||
desired_payload = plistlib.dumps(desired, fmt=plistlib.FMT_XML, sort_keys=True)
|
||||
return MissionCoreLaunchAgentPlan(
|
||||
agent_path=path,
|
||||
@@ -244,9 +232,7 @@ def _private_local_worker_directory(path: Path, label: str) -> Path:
|
||||
or stat.S_IMODE(metadata.st_mode) != 0o700
|
||||
or metadata.st_uid != os.getuid()
|
||||
):
|
||||
raise MissionCoreLaunchAgentError(
|
||||
f"{label} is not a private canonical directory"
|
||||
)
|
||||
raise MissionCoreLaunchAgentError(f"{label} is not a private canonical directory")
|
||||
return resolved
|
||||
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ from typing import Any, cast
|
||||
import numpy as np
|
||||
import rerun as rr
|
||||
|
||||
from k1link.cache_budget import cache_publication, require_cache_room
|
||||
from k1link.laboratory.canonical_rerun_overlay import (
|
||||
APPLICATION_ID,
|
||||
CanonicalLabOverlayArtifact,
|
||||
@@ -198,6 +199,12 @@ class PortableReplayService:
|
||||
self.cache.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if self.cache.is_symlink() or shutil.disk_usage(self.cache).free < 3 * 1024**3:
|
||||
raise PortableReplayError("replay cache has insufficient safe space")
|
||||
require_cache_room(
|
||||
self.cache,
|
||||
1024**3,
|
||||
kind="observatory-portable-replay-cache",
|
||||
error_type=PortableReplayError,
|
||||
)
|
||||
with tempfile.TemporaryDirectory(prefix=".pack-", dir=self.cache) as temporary:
|
||||
root = Path(temporary)
|
||||
proxy = self._video(epoch, root)
|
||||
@@ -231,10 +238,16 @@ class PortableReplayService:
|
||||
"sha256": artifact.sha256,
|
||||
"byte_length": artifact.byte_length,
|
||||
}
|
||||
staged = self.cache / f".{key}.json"
|
||||
staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, self.cache / f"{key}.json")
|
||||
with cache_publication(
|
||||
self.cache,
|
||||
65536,
|
||||
kind="observatory-portable-replay-cache",
|
||||
error_type=PortableReplayError,
|
||||
):
|
||||
staged = self.cache / f".{key}.json"
|
||||
staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, self.cache / f"{key}.json")
|
||||
return artifact
|
||||
|
||||
def _composition_key(
|
||||
@@ -381,6 +394,12 @@ class PortableReplayService:
|
||||
self.cache.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if self.cache.is_symlink() or shutil.disk_usage(self.cache).free < 3 * 1024**3:
|
||||
raise PortableReplayError("replay cache has insufficient safe space")
|
||||
require_cache_room(
|
||||
self.cache,
|
||||
1024**3,
|
||||
kind="observatory-portable-replay-cache",
|
||||
error_type=PortableReplayError,
|
||||
)
|
||||
with tempfile.TemporaryDirectory(
|
||||
prefix=".pack-composition-", dir=self.cache
|
||||
) as temporary:
|
||||
@@ -416,10 +435,16 @@ class PortableReplayService:
|
||||
"sha256": artifact.sha256,
|
||||
"byte_length": artifact.byte_length,
|
||||
}
|
||||
staged = self.cache / f".{key}.json"
|
||||
staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, self.cache / f"{key}.json")
|
||||
with cache_publication(
|
||||
self.cache,
|
||||
65536,
|
||||
kind="observatory-portable-replay-cache",
|
||||
error_type=PortableReplayError,
|
||||
):
|
||||
staged = self.cache / f".{key}.json"
|
||||
staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, self.cache / f"{key}.json")
|
||||
return artifact
|
||||
|
||||
def _camera(self, session_id: str, bundle: dict[str, Any]) -> RecordedMediaEpoch:
|
||||
@@ -519,11 +544,17 @@ class PortableReplayService:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
metadata = {"sha256": digest, "byte_length": proxy.stat().st_size}
|
||||
os.chmod(proxy, 0o600)
|
||||
os.replace(proxy, saved)
|
||||
staged = root / "camera.json"
|
||||
staged.write_text(json.dumps(metadata), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, saved_manifest)
|
||||
with cache_publication(
|
||||
self.cache,
|
||||
65536,
|
||||
kind="observatory-portable-replay-cache",
|
||||
error_type=PortableReplayError,
|
||||
):
|
||||
os.replace(proxy, saved)
|
||||
staged = root / "camera.json"
|
||||
staged.write_text(json.dumps(metadata), encoding="utf-8")
|
||||
os.chmod(staged, 0o600)
|
||||
os.replace(staged, saved_manifest)
|
||||
return saved
|
||||
|
||||
|
||||
|
||||
@@ -10,14 +10,10 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from k1link.launchd_logs import launchd_log_path
|
||||
from k1link.launchd_logs import bounded_launchd_output, launchd_log_path
|
||||
|
||||
OBSERVATORY_WORKER_TUNNEL_LABEL: Final = (
|
||||
"com.nodedc.observatory-worker-tunnel.local"
|
||||
)
|
||||
OBSERVATORY_WORKER_TUNNEL_SCHEMA: Final = (
|
||||
"missioncore.observatory-worker-tunnel-plan/v1"
|
||||
)
|
||||
OBSERVATORY_WORKER_TUNNEL_LABEL: Final = "com.nodedc.observatory-worker-tunnel.local"
|
||||
OBSERVATORY_WORKER_TUNNEL_SCHEMA: Final = "missioncore.observatory-worker-tunnel-plan/v1"
|
||||
OBSERVATORY_WORKER_TUNNEL_PORT: Final = 18080
|
||||
|
||||
|
||||
@@ -97,6 +93,7 @@ def plan_observatory_worker_tunnel_launch_agent(
|
||||
"StandardOutPath": str(log_path),
|
||||
"StandardErrorPath": str(log_path),
|
||||
}
|
||||
desired = bounded_launchd_output(desired, Path(__file__).resolve().parents[3])
|
||||
payload = plistlib.dumps(desired, fmt=plistlib.FMT_XML, sort_keys=True)
|
||||
return ObservatoryWorkerTunnelLaunchAgentPlan(
|
||||
agent_path=target_path,
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Bounded binary stdout/stderr journal for one launchd-owned child process.
|
||||
|
||||
The parent drains a pipe and owns rotation; no copy/truncate race with a writer.
|
||||
It does not change the child's arguments, environment, credentials or network.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import os
|
||||
import selectors
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
MAX_BYTES = 8 * 1024**2
|
||||
BACKUPS = 4
|
||||
|
||||
|
||||
class Journal:
|
||||
def __init__(self, path: Path, *, max_bytes=MAX_BYTES, backups=BACKUPS):
|
||||
if max_bytes < 1 or not 1 <= backups <= 20:
|
||||
raise ValueError("Invalid journal limits")
|
||||
self.path = path.absolute()
|
||||
self.max_bytes, self.backups = max_bytes, backups
|
||||
self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if self.path.parent.resolve() != self.path.parent:
|
||||
raise ValueError("Journal parent is not canonical")
|
||||
self.lock = self._open(self.path.with_name(self.path.name + ".lock"))
|
||||
try:
|
||||
fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
self.fd = self._open(self.path)
|
||||
except BaseException:
|
||||
os.close(self.lock)
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def _open(path):
|
||||
fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_APPEND | os.O_NOFOLLOW, 0o600)
|
||||
info = os.fstat(fd)
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid():
|
||||
os.close(fd)
|
||||
raise ValueError("Journal must be an owned, unlinked regular file")
|
||||
os.fchmod(fd, 0o600)
|
||||
return fd
|
||||
|
||||
def _rotate(self):
|
||||
# Validate every managed destination before changing the rotation set.
|
||||
paths = [self.path] + [Path(f"{self.path}.{i}") for i in range(1, self.backups + 1)]
|
||||
for p in paths:
|
||||
if p.exists() or p.is_symlink():
|
||||
s = p.lstat()
|
||||
if not stat.S_ISREG(s.st_mode) or s.st_nlink != 1 or s.st_uid != os.getuid():
|
||||
raise ValueError("Unsafe journal rotation target")
|
||||
named = self.path.stat()
|
||||
opened = os.fstat(self.fd)
|
||||
if (named.st_dev, named.st_ino) != (opened.st_dev, opened.st_ino):
|
||||
raise ValueError("Journal identity changed")
|
||||
os.close(self.fd)
|
||||
self.fd = -1
|
||||
try:
|
||||
paths[-1].unlink(missing_ok=True)
|
||||
for index in range(self.backups - 1, -1, -1):
|
||||
if paths[index].exists():
|
||||
os.replace(paths[index], paths[index + 1])
|
||||
finally:
|
||||
self.fd = self._open(self.path)
|
||||
|
||||
def write(self, payload: bytes):
|
||||
view = memoryview(payload)
|
||||
while view:
|
||||
space = self.max_bytes - os.fstat(self.fd).st_size
|
||||
if space <= 0:
|
||||
self._rotate()
|
||||
space = self.max_bytes
|
||||
written = os.write(self.fd, view[:space])
|
||||
if written <= 0:
|
||||
raise OSError("Journal write made no progress")
|
||||
view = view[written:]
|
||||
|
||||
def close(self):
|
||||
if self.fd >= 0:
|
||||
os.close(self.fd)
|
||||
self.fd = -1
|
||||
if self.lock >= 0:
|
||||
os.close(self.lock)
|
||||
self.lock = -1
|
||||
|
||||
|
||||
def supervise(command, path: Path, *, max_bytes=MAX_BYTES, backups=BACKUPS):
|
||||
journal = Journal(path, max_bytes=max_bytes, backups=backups)
|
||||
child = None
|
||||
previous = {}
|
||||
deadline = None
|
||||
dropped = 0
|
||||
try:
|
||||
child = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
assert child.stdout is not None
|
||||
|
||||
def stop(signum, _frame):
|
||||
nonlocal deadline
|
||||
if child.poll() is None:
|
||||
child.send_signal(signum)
|
||||
deadline = time.monotonic() + 12
|
||||
|
||||
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
|
||||
previous[signum] = signal.signal(signum, stop)
|
||||
with selectors.DefaultSelector() as selector:
|
||||
selector.register(child.stdout, selectors.EVENT_READ)
|
||||
exited = None
|
||||
eof = False
|
||||
while True:
|
||||
if deadline is not None and time.monotonic() >= deadline and child.poll() is None:
|
||||
child.kill()
|
||||
ready = selector.select(0.25)
|
||||
if ready:
|
||||
chunk = os.read(child.stdout.fileno(), 65536)
|
||||
if not chunk:
|
||||
selector.unregister(child.stdout)
|
||||
eof = True
|
||||
try:
|
||||
if dropped:
|
||||
journal.write(
|
||||
f"\n[journal recovered; dropped {dropped} bytes]\n".encode()
|
||||
)
|
||||
dropped = 0
|
||||
journal.write(chunk)
|
||||
except (OSError, ValueError):
|
||||
# A full/unavailable disk must not deadlock the operator service.
|
||||
# The loss counter is bounded state, not an in-memory log backlog.
|
||||
dropped = min(2**63 - 1, dropped + len(chunk))
|
||||
if child.poll() is not None:
|
||||
if eof:
|
||||
break
|
||||
exited = exited or time.monotonic()
|
||||
if time.monotonic() - exited >= 2:
|
||||
break # A descendant must not keep a dead service's pipe alive forever.
|
||||
child.stdout.close()
|
||||
code = child.wait()
|
||||
return code if code >= 0 else 128 - code
|
||||
finally:
|
||||
if child is not None and child.poll() is None:
|
||||
child.terminate()
|
||||
try:
|
||||
child.wait(timeout=12)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
child.wait()
|
||||
for signum, handler in previous.items():
|
||||
signal.signal(signum, handler)
|
||||
journal.close()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--log", type=Path, required=True)
|
||||
parser.add_argument("command", nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
command = args.command[1:] if args.command[:1] == ["--"] else args.command
|
||||
if not command:
|
||||
parser.error("child command is required")
|
||||
return supervise(command, args.log)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -10,6 +10,8 @@ from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.cache_budget import CacheCapacityError, cache_publication
|
||||
|
||||
from .media import RecordedMediaEpoch, RecordedMediaInspector, RecordedMediaManifest
|
||||
from .models import SessionIntegrityError
|
||||
from .store import SessionStore
|
||||
@@ -133,7 +135,14 @@ class RecordedCameraFrameService:
|
||||
return cached
|
||||
self._require_latest(lane, ticket)
|
||||
frame = self._decode(manifest, epoch, sequence)
|
||||
_publish_cached_jpeg(cache_path, frame.payload)
|
||||
try:
|
||||
with cache_publication(
|
||||
self._cache_root, len(frame.payload), kind="camera-frame-cache"
|
||||
):
|
||||
_publish_cached_jpeg(cache_path, frame.payload)
|
||||
except CacheCapacityError:
|
||||
# The validated decoded frame is still usable without a disk copy.
|
||||
pass
|
||||
self._require_latest(lane, ticket)
|
||||
return frame
|
||||
finally:
|
||||
|
||||
@@ -15,6 +15,7 @@ from pathlib import Path
|
||||
from typing import Any, TypeGuard
|
||||
|
||||
from k1link import media_fragments as _fragment_timing
|
||||
from k1link.cache_budget import CacheCapacityError, cache_publication
|
||||
|
||||
from .models import RecordedMediaArtifact, ReplayCommand, SessionIntegrityError
|
||||
|
||||
@@ -255,11 +256,15 @@ class RecordedMediaInspector:
|
||||
if root is None:
|
||||
return
|
||||
payload = _encode_prepared_sidecar(manifest, identity)
|
||||
_write_sidecar_atomic(
|
||||
root,
|
||||
_sidecar_name(manifest.session_id, manifest.artifact_id),
|
||||
payload,
|
||||
)
|
||||
try:
|
||||
with cache_publication(root, len(payload), kind="camera-media-index"):
|
||||
_write_sidecar_atomic(
|
||||
root,
|
||||
_sidecar_name(manifest.session_id, manifest.artifact_id),
|
||||
payload,
|
||||
)
|
||||
except CacheCapacityError:
|
||||
pass
|
||||
|
||||
def get_prepared(
|
||||
self,
|
||||
|
||||
@@ -8,6 +8,7 @@ import shutil
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.cache_budget import cache_publication
|
||||
from k1link.simulation.ai_polygon.plans import PlanStore
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
@@ -75,7 +76,8 @@ class EditorCache:
|
||||
else:
|
||||
if shutil.disk_usage(self.root).free < LIMIT + 512 * 1024**2:
|
||||
raise ValueError("Недостаточно места для локальной копии сцены.")
|
||||
path.mkdir(mode=0o700, exist_ok=True)
|
||||
with cache_publication(self.root, 65536, kind="editor-cache", max_files=4096):
|
||||
path.mkdir(mode=0o700, exist_ok=True)
|
||||
row = {
|
||||
"key": key,
|
||||
"identity": identity,
|
||||
@@ -85,9 +87,13 @@ class EditorCache:
|
||||
"error": None,
|
||||
}
|
||||
if world.get("local_scene"):
|
||||
row.update(status="ready", files=self.worlds.projects.cache_files(world),
|
||||
local_scene=world["local_scene"])
|
||||
write_json(path / "manifest.json", row)
|
||||
row.update(
|
||||
status="ready",
|
||||
files=self.worlds.projects.cache_files(world),
|
||||
local_scene=world["local_scene"],
|
||||
)
|
||||
with cache_publication(self.root, 65536, kind="editor-cache", max_files=4096):
|
||||
write_json(path / "manifest.json", row)
|
||||
return row
|
||||
|
||||
def pending(self):
|
||||
@@ -137,7 +143,20 @@ class EditorCache:
|
||||
and files["collision.glb"]["sha256"] != row["identity"]["collider_sha256"]
|
||||
):
|
||||
raise ValueError("Collider identity mismatch")
|
||||
row.update(files=files, status="uploading")
|
||||
# Reserve all declared remaining transfers in the existing manifests.
|
||||
# No extra reservation files or abandoned-expiry deletion are needed.
|
||||
remaining = sum(a["byte_length"] for a in files.values()) - sum(
|
||||
a.get("uploaded_bytes", 0) for a in row.get("files", {}).values()
|
||||
)
|
||||
with cache_publication(
|
||||
self.root,
|
||||
self._pending_bytes(exclude=key) + remaining + 65536,
|
||||
kind="editor-cache",
|
||||
max_files=4096,
|
||||
):
|
||||
row.update(files=files, status="uploading")
|
||||
write_json(path / "manifest.json", row)
|
||||
return self.get(key)
|
||||
elif action == "chunk":
|
||||
name = body.get("name")
|
||||
if name not in FILES or name not in row["files"] or row["status"] != "uploading":
|
||||
@@ -154,7 +173,15 @@ class EditorCache:
|
||||
raise ValueError("Invalid editor chunk")
|
||||
if shutil.disk_usage(path).free < len(payload) + 512 * 1024**2:
|
||||
raise ValueError("Недостаточно места для сцены.")
|
||||
with (path / (name + ".part")).open("ab") as stream:
|
||||
with (
|
||||
cache_publication(
|
||||
self.root,
|
||||
self._pending_bytes() + 65536,
|
||||
kind="editor-cache",
|
||||
max_files=4096,
|
||||
),
|
||||
(path / (name + ".part")).open("ab") as stream,
|
||||
):
|
||||
stream.write(payload)
|
||||
elif action == "complete":
|
||||
for name, asset in row["files"].items():
|
||||
@@ -180,6 +207,20 @@ class EditorCache:
|
||||
write_json(path / "manifest.json", row)
|
||||
return self.get(key)
|
||||
|
||||
def _pending_bytes(self, exclude=None):
|
||||
remaining = 0
|
||||
for manifest in self.root.glob("*/manifest.json"):
|
||||
if manifest.parent.name == exclude:
|
||||
continue
|
||||
row = self.get(manifest.parent.name)
|
||||
if row.get("local_scene") or row["status"] not in {"queued", "preparing", "uploading"}:
|
||||
continue
|
||||
remaining += sum(
|
||||
max(0, a["byte_length"] - a.get("uploaded_bytes", 0))
|
||||
for a in row.get("files", {}).values()
|
||||
)
|
||||
return remaining
|
||||
|
||||
def asset(self, key, name):
|
||||
row = self.get(key)
|
||||
if row["status"] != "ready" or name not in FILES:
|
||||
|
||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
from typing import Final
|
||||
from uuid import uuid4
|
||||
|
||||
from k1link.cache_budget import CacheCapacityError, cache_publication
|
||||
from k1link.compute.lidar_field_review import E10LidarFieldSource
|
||||
from k1link.compute.lidar_ground import LidarGroundError
|
||||
from k1link.compute.lidar_local_surface import (
|
||||
@@ -68,9 +69,7 @@ class K1LocalSurfaceReadService:
|
||||
) -> None:
|
||||
if max_entries < 1:
|
||||
raise ValueError("LiDAR reader cache must retain at least one entry")
|
||||
self.cache_root = (
|
||||
cache_root.expanduser().absolute() if cache_root is not None else None
|
||||
)
|
||||
self.cache_root = cache_root.expanduser().absolute() if cache_root is not None else None
|
||||
self.max_entries = max_entries
|
||||
self._lock = threading.RLock()
|
||||
self._models: OrderedDict[Path, _ModelEntry] = OrderedDict()
|
||||
@@ -124,10 +123,7 @@ class K1LocalSurfaceReadService:
|
||||
) -> tuple[K1LocalSurfaceV1, E10LidarFieldSource]:
|
||||
model = self._model(model_path)
|
||||
source_pack_id = model.identity.get("source_pack_id")
|
||||
if (
|
||||
not isinstance(source_pack_id, str)
|
||||
or _E10_PACK_ID.fullmatch(source_pack_id) is None
|
||||
):
|
||||
if not isinstance(source_pack_id, str) or _E10_PACK_ID.fullmatch(source_pack_id) is None:
|
||||
raise LidarGroundError("K1 local-surface source id is invalid")
|
||||
source_path = source_root / source_pack_id
|
||||
if not source_path.is_dir():
|
||||
@@ -254,19 +250,23 @@ class K1LocalSurfaceReadService:
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
descriptor = os.open(
|
||||
temporary,
|
||||
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
|
||||
0o600,
|
||||
)
|
||||
try:
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, destination)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
with cache_publication(root, len(payload), kind="lidar-read-cache"):
|
||||
descriptor = os.open(
|
||||
temporary,
|
||||
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
|
||||
0o600,
|
||||
)
|
||||
try:
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, destination)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
except CacheCapacityError:
|
||||
return
|
||||
|
||||
def _evict_models(self) -> None:
|
||||
while len(self._models) > self.max_entries:
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import stat
|
||||
from datetime import UTC, datetime
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
@@ -116,7 +117,7 @@ class ScannerDiagnosticJsonFormatter(logging.Formatter):
|
||||
for field in _EXTRA_FIELDS:
|
||||
value = getattr(record, field, None)
|
||||
if value is not None and isinstance(value, (str, int, bool)):
|
||||
document[field] = value
|
||||
document[field] = value[:256] if isinstance(value, str) else value
|
||||
if record.exc_info is not None:
|
||||
exception_type, _exception, traceback = record.exc_info
|
||||
if exception_type is not None:
|
||||
@@ -137,7 +138,28 @@ class ScannerDiagnosticJsonFormatter(logging.Formatter):
|
||||
for value in properties
|
||||
):
|
||||
document["write_characteristic_properties"] = sorted(set(properties))
|
||||
return json.dumps(document, ensure_ascii=False, separators=(",", ":"))
|
||||
payload = json.dumps(document, ensure_ascii=False, separators=(",", ":"))
|
||||
# An oversized extra field cannot bypass the rotation budget in one record.
|
||||
for field in reversed(_EXTRA_FIELDS):
|
||||
if len(payload.encode("utf-8")) <= 16384:
|
||||
break
|
||||
document.pop(field, None)
|
||||
document["fields_omitted"] = True
|
||||
payload = json.dumps(document, ensure_ascii=False, separators=(",", ":"))
|
||||
return payload
|
||||
|
||||
|
||||
class PrivateRotatingFileHandler(RotatingFileHandler):
|
||||
def _open(self):
|
||||
descriptor = os.open(
|
||||
self.baseFilename, os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600
|
||||
)
|
||||
info = os.fstat(descriptor)
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid():
|
||||
os.close(descriptor)
|
||||
raise ValueError("Invalid diagnostic journal")
|
||||
os.fchmod(descriptor, 0o600)
|
||||
return os.fdopen(descriptor, "a", encoding=self.encoding, errors=self.errors)
|
||||
|
||||
|
||||
def configure_scanner_diagnostics(logs_root: Path) -> Path:
|
||||
@@ -151,7 +173,7 @@ def configure_scanner_diagnostics(logs_root: Path) -> Path:
|
||||
if getattr(handler, _HANDLER_MARKER, None) == str(target):
|
||||
return target
|
||||
|
||||
handler = RotatingFileHandler(
|
||||
handler = PrivateRotatingFileHandler(
|
||||
target,
|
||||
maxBytes=5 * 1024 * 1024,
|
||||
backupCount=5,
|
||||
|
||||
Reference in New Issue
Block a user