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:
DCCONSTRUCTIONS
2026-10-29 09:09:58 +03:00
parent 55f64f195b
commit 70ef3f9f1c
119 changed files with 3128 additions and 331 deletions
+476
View File
@@ -0,0 +1,476 @@
"""Lifecycle, dependency and failure acceptance for local intermediate retention."""
import hashlib
import importlib.util
import json
import os
import shutil
import zipfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest.mock import patch
import pytest
MODULE = Path(__file__).resolve().parents[1] / "scripts/packaging/build_retention.py"
spec = importlib.util.spec_from_file_location("build_retention", MODULE)
retention = importlib.util.module_from_spec(spec)
spec.loader.exec_module(retention)
Store = retention.BuildRetention
Error = retention.RetentionError
NODE = "apps/node-agent/build"
X4 = "plugins/insta360-x4/build"
@pytest.fixture
def store(tmp_path):
for directory in (NODE, X4):
(tmp_path / directory).mkdir(parents=True)
return Store(tmp_path)
def content(index, *, line="node/node-only", base=None):
if line.startswith("node/"):
manifest = {
"schema": "missioncore.node.linux-build-source/v1",
"profile": line.split("/")[1],
}
directory, prefix, member = NODE, "mission-core-node-linux-build", "source.json"
elif line == "x4/owner":
manifest = {"schema": "missioncore.insta360.owner-wrapper-build/v1"}
directory, prefix, member = X4, "mission-core-x4-owner-build", "manifest.json"
else:
kind = line.split("/")[1]
manifest = {"schema": "missioncore.insta360.build-source/v1"}
if kind == "package":
manifest["kind"] = kind
directory, prefix, member = (
X4,
"mission-core-x4-" + ("package-" if kind == "package" else "") + "build",
"source.json",
)
manifest["test_nonce"] = index
if base:
manifest["base"] = base
raw = json.dumps(manifest).encode()
relative = f"{directory}/{prefix}-{hashlib.sha256(raw).hexdigest()[:24]}.pyz"
return relative, member, raw
def make(store, index, *, line="node/node-only", base=None, managed=True, outcome="intermediate"):
relative, member, raw = content(index, line=line, base=base)
output = store.root / relative
if managed:
with (
store.publish(output, required_bytes=1024) as temporary,
zipfile.ZipFile(temporary, "x") as archive,
):
archive.writestr(member, raw)
owner = store._state()["inputs"][relative]["owner"]
if outcome:
store.finish(relative, owner=owner, outcome=outcome, reason="test outcome")
else:
with zipfile.ZipFile(output, "x") as archive:
archive.writestr(member, raw)
return relative
def actions(store):
plan = store.plan()
assert not plan["errors"], plan["errors"]
return {x["path"]: x["action"] for x in plan["inputs"]}
def base_ref(store, relative):
return {
"name": Path(relative).name,
"sha256": hashlib.sha256((store.root / relative).read_bytes()).hexdigest(),
}
def test_plan_is_read_only_and_legacy_is_protected(store):
old = make(store, 1, managed=False)
assert actions(store)[old] == "retain"
assert not store.control.exists()
plan = store.plan()
receipt = store.apply(plan)
assert receipt["removed"] == [] and (store.root / old).exists()
def test_two_completed_per_independent_line(store):
names = {}
for line in ("node/node-only", "node/node-core", "x4/native", "x4/package", "x4/owner"):
names[line] = [make(store, i, line=line) for i in range(4)]
plan = store.plan()
assert sum(x["action"] == "delete" for x in plan["inputs"]) == 10
receipt = store.apply(plan)
assert len(receipt["removed"]) == 10
for line in names:
assert [(store.root / n).exists() for n in names[line]] == [False, False, True, True]
assert store.apply(store.plan())["removed"] == []
def test_transitive_base_closure_keeps_exact_old_bytes(store):
base = make(store, 0)
delta = make(store, 1, base=base_ref(store, base))
tail = make(store, 2, base=base_ref(store, delta))
make(store, 3)
assert all(actions(store)[n] == "retain" for n in (base, delta, tail))
store.apply(store.plan())
assert not store.plan()["errors"]
@pytest.mark.parametrize("outcome", ["qualified", "rollback"])
def test_pins_are_extra_to_two_intermediates_and_need_explicit_release(store, outcome):
pin = make(store, 0, outcome=outcome)
normal = [make(store, i) for i in range(1, 4)]
assert actions(store)[pin] == "retain"
assert actions(store)[normal[0]] == "delete"
plan = store.plan()
store.pin(normal[0], pin="external-release", reason="qualified externally")
with pytest.raises(Error, match="Stale"):
store.apply(plan)
store.pin(pin, pin=outcome, reason="explicit retirement", remove=True)
assert actions(store)[pin] == "delete"
@pytest.mark.parametrize("outcome", ["intermediate", "failed", "cancelled"])
def test_active_owner_survives_restarts_until_explicit_terminal_result(store, outcome):
active = make(store, 0, outcome=None)
for i in range(1, 4):
make(store, i)
restarted = Store(store.root)
assert actions(restarted)[active] == "retain"
with pytest.raises(Error, match="owner"):
restarted.finish(active, owner="wrong", outcome=outcome, reason="done")
owner = restarted._state()["inputs"][active]["owner"]
restarted.finish(active, owner=owner, outcome=outcome, reason="confirmed terminal")
assert actions(restarted)[active] == "delete"
def test_legacy_adoption_cannot_silently_make_data_disposable(store):
old = make(store, 0, managed=False)
store.adopt(old, pin="legacy-review", reason="unique provenance")
for i in range(1, 4):
make(store, i)
assert actions(store)[old] == "retain"
store.pin(old, pin="legacy-review", remove=True, reason="confirmed intermediate only")
assert actions(store)[old] == "delete"
def test_unknown_releases_evidence_and_noninput_files_never_selected(store):
protected = [
".runtime/mission-core/recordings/evidence.pyz",
"private/releases/a.pyz",
NODE + "/mission-core-node-install-" + "f" * 24 + ".pyz",
NODE + "/qualified/result.json",
X4 + "/sdk/unique.zip",
]
for n in protected:
path = store.root / n
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"unique")
for i in range(3):
make(store, i)
store.apply(store.plan())
assert all((store.root / n).read_bytes() == b"unique" for n in protected)
@pytest.mark.parametrize("mutation", ["bytes", "new-input", "edited-plan", "pin"])
def test_stale_plan_rejected_before_any_unlink(store, mutation):
names = [make(store, i) for i in range(4)]
plan = store.plan()
if mutation == "bytes":
with (store.root / names[0]).open("ab") as stream:
stream.write(b"changed")
elif mutation == "new-input":
make(store, 5, managed=False)
elif mutation == "edited-plan":
plan["inputs"][0]["action"] = "surprise"
else:
store.pin(names[0], pin="new-release", reason="new qualification")
with pytest.raises(Error, match="Stale"):
store.apply(plan)
assert all((store.root / n).exists() for n in names)
def test_symlink_and_path_escape_fail_closed(store, tmp_path):
names = [make(store, i) for i in range(3)]
path = store.root / names[0]
path.unlink()
path.symlink_to(store.root / names[1])
plan = store.plan()
assert plan["errors"] and all(x["action"] == "retain" for x in plan["inputs"])
with pytest.raises(Error, match="errors"):
store.apply(plan)
for name in ("../outside.pyz", "/tmp/a.pyz", ".runtime/mission-core/a.pyz"):
with pytest.raises(Error):
store._path(name)
shutil.rmtree(store.root / X4)
(store.root / X4).symlink_to(store.root / NODE, target_is_directory=True)
assert store.plan()["errors"]
def test_changed_base_and_malformed_archive_block_all_deletions(store):
base = make(store, 0)
make(store, 1, base=base_ref(store, base))
for i in range(2, 5):
make(store, i)
with (store.root / base).open("ab") as f:
f.write(b"corrupt")
plan = store.plan()
assert any("base" in x for x in plan["errors"])
assert all(x["action"] == "retain" for x in plan["inputs"])
bad = store.root / NODE / "mission-core-node-linux-build-notanid.pyz"
bad.write_bytes(b"incomplete")
assert any("notanid" in x for x in store.plan()["errors"])
def test_failed_publication_removes_only_own_temporary(store):
relative, _, _ = content(0)
before = set((store.root / NODE).iterdir())
with pytest.raises(ValueError), store.publish(store.root / relative) as temporary:
temporary.write_bytes(b"partial")
raise ValueError("compiler failed")
assert set((store.root / NODE).iterdir()) == before
assert not store._state()["inputs"]
def test_publication_rejects_missing_base_without_exposing_archive(store):
relative, member, raw = content(
1, base={"name": "mission-core-node-linux-build-" + "a" * 24 + ".pyz", "sha256": "b" * 64}
)
with (
pytest.raises(FileNotFoundError),
store.publish(store.root / relative) as temporary,
zipfile.ZipFile(temporary, "x") as z,
):
z.writestr(member, raw)
assert not (store.root / relative).exists()
assert not list((store.root / NODE).glob(".retention-*"))
def test_capacity_refusal_preserves_all_inputs(store):
for i in range(8):
make(store, i, outcome=None)
relative, _, _ = content(8)
with pytest.raises(Error, match="unfinished"), store.publish(store.root / relative):
pytest.fail("must not start")
disk = shutil.disk_usage(store.root)
with patch.object(
retention.shutil, "disk_usage", return_value=type(disk)(disk.total, disk.used, 0)
):
other, _, _ = content(0, line="x4/native")
with pytest.raises(Error, match="space"), store.publish(store.root / other):
pytest.fail("must not start")
assert len(store.plan()["inputs"]) == 8
def test_concurrent_publications_have_distinct_persistent_owners(store):
with ThreadPoolExecutor(max_workers=2) as pool:
names = list(pool.map(lambda i: make(store, i, outcome=None), range(2)))
state = store._state()
assert len({state["inputs"][n]["owner"] for n in names}) == 2
assert not store.plan()["errors"]
def test_unlink_failure_is_journaled_and_remaining_graph_is_valid(store):
base = make(store, 0)
delta = make(store, 1, base=base_ref(store, base))
make(store, 2)
make(store, 3)
unlink = Path.unlink
def fail(path, *args, **kwargs):
if str(path) == str(store.root / base):
raise OSError("simulated busy storage")
return unlink(path, *args, **kwargs)
with patch.object(Path, "unlink", fail), pytest.raises(OSError, match="simulated"):
store.apply(store.plan())
assert not (store.root / delta).exists() and (store.root / base).exists()
receipt_path = next((store.control / "receipts").glob("*.json"))
receipt = json.loads(receipt_path.read_text())
assert receipt["status"] == "interrupted" and receipt["removed"][0]["path"] == delta
assert not store.plan()["errors"]
assert store.recover(receipt_path.name)["deleted_now"] == 0
store.apply(store.plan())
assert not (store.root / base).exists()
def test_recover_crash_between_unlink_and_registry_commit(store):
old = make(store, 0)
make(store, 1)
make(store, 2)
with (
patch.object(store, "_save", side_effect=OSError("simulated state write failure")),
pytest.raises(OSError, match="state write"),
):
store.apply(store.plan())
assert not (store.root / old).exists() and store.plan()["errors"]
receipt_path = next((store.control / "receipts").glob("*.json"))
result = store.recover(receipt_path.name)
assert result["recovered_missing"] == [old] and result["deleted_now"] == 0
assert not store.plan()["errors"]
def test_hardlinked_other_copy_survives_and_bytes_are_only_upper_bound(store):
old = make(store, 0)
other = store.root / "rollback-copy.pyz"
os.link(store.root / old, other)
expected = other.read_bytes()
make(store, 1)
make(store, 2)
assert store.plan()["candidate_bytes_upper_bound"] == len(expected)
store.apply(store.plan())
assert other.read_bytes() == expected
def load_producer(relative, monkeypatch):
source = MODULE.parents[2] / relative
monkeypatch.syspath_prepend(str(source.parent))
module_spec = importlib.util.spec_from_file_location("producer_" + source.stem, source)
module = importlib.util.module_from_spec(module_spec)
module_spec.loader.exec_module(module)
return module
def producer_hooks(module, store, monkeypatch):
monkeypatch.setattr(module, "publish_input", store.publish)
def hold(output):
relative = str(output.relative_to(store.root))
return {"owner": store._state()["inputs"][relative]["owner"], "path": relative}
monkeypatch.setattr(module, "input_hold", hold)
@pytest.mark.parametrize("kind", ["native", "package", "owner", "node"])
def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeypatch, capsys, kind):
# Exercise the real producer wrappers with tiny synthetic inputs. No SDK execution,
# compiler, board, network or production build is involved.
def write(name, data=b"fixture"):
path = store.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def document(name, data):
return write(name, json.dumps(data).encode())
xroot = store.root / "plugins/insta360-x4"
nroot = store.root / "apps/node-agent"
for name in ("bridge.cpp", "bridge.h", "tests/fake_sdk.cpp", "tests/check_abi.py"):
write("plugins/insta360-x4/native/" + name)
for name in (
"build_native.py",
"build_native_entry.py",
"native_build_entry.py",
"fetch_sdk.py",
"install",
"install_release.py",
"owner_release_entry.py",
"build_owner_release.py",
"preinst",
"postinst",
"prerm",
"postrm",
):
write("plugins/insta360-x4/packaging/" + name)
lock = document("plugins/insta360-x4/packaging/sdk-lock.json", {"files": []})
if kind == "native":
module = load_producer(
"plugins/insta360-x4/packaging/build_source_artifact.py", monkeypatch
)
monkeypatch.setattr(module, "ROOT", xroot)
monkeypatch.setattr(module, "LOCK", lock)
monkeypatch.setattr(module, "verify", lambda *args: None)
elif kind == "package":
module = load_producer(
"plugins/insta360-x4/packaging/build_package_artifact.py", monkeypatch
)
monkeypatch.setattr(module, "ROOT", xroot)
monkeypatch.setattr(module, "REPOSITORY", store.root)
monkeypatch.setattr(module, "verify", lambda *args: None)
document("plugins/insta360-x4/packaging/python-lock.json", {"wheels": []})
for name in ("libmissioncore_x4.so", "provenance.json"):
write("plugins/insta360-x4/build/native/" + name)
for name in (
"scripts/packaging/debian.py",
"apps/node-agent/packaging/insta360_profile.py",
"apps/node-agent/packaging/install_owner_release.py",
"apps/node-agent/packaging/can_maintenance.py",
"apps/node-agent/packaging/vesc_hall_recovery.py",
"src/k1link/__init__.py",
"src/k1link/fleet/__init__.py",
"src/k1link/fleet/sensors.py",
"src/k1link/fleet/trust.py",
):
write(name)
elif kind == "owner":
module = load_producer("plugins/insta360-x4/packaging/build_owner_builder.py", monkeypatch)
monkeypatch.setattr(module, "ROOT", xroot)
report = document(
"qualified-report.json", {"sha256": "f" * 64, "bytes": 0, "file": "qualified.deb"}
)
else:
module = load_producer("apps/node-agent/packaging/build_linux_source.py", monkeypatch)
monkeypatch.setattr(module, "NODE", nroot)
monkeypatch.setattr(module, "REPO", store.root)
# DG stays inside this tiny fixture; no duplicate source checkout.
dg = store.root / "design-fixture"
monkeypatch.setattr(module, "DG", dg)
for name in (
"package.json",
"package-lock.json",
"tsconfig.base.json",
"apps/catalog/package.json",
):
write("design-fixture/" + name)
monkeypatch.setattr(module, "files", lambda root: [])
monkeypatch.setattr(
module.subprocess, "check_output", lambda *args, **kwargs: module.DG_COMMIT
)
document("apps/node-agent/packaging/linux-toolchains.json", {"files": []})
document("apps/node-agent/packaging/realsense-bundle.json", {"wheels": []})
package = write("mission-core-insta360-x4_0.1.0_amd64.deb")
digest = hashlib.sha256(package.read_bytes()).hexdigest()
document(
"apps/node-agent/packaging/insta360-profile.json",
{"version": "0.1.0", "bytes": 7, "sha256": digest},
)
write("plugins/vesc/build/native-runtime/native.so")
document(
"plugins/vesc/packaging/native-runtime.json",
{"file": "native.so", "bytes": 7, "sha256": digest},
)
document("plugins/vesc/packaging/firmware-catalog.json", {"items": []})
write("plugins/vesc/build/package-catalog/vesc_pkg_all.rcc")
document("plugins/vesc/packaging/package-catalog.json", {"bytes": 7, "sha256": digest})
write("plugins/usb-can/build/sdk/libcontrolcanfd.so")
monkeypatch.setattr(module, "USB_CAN_SDK_SHA256", digest)
write("apps/node-agent/packaging/linux_build_entry.py")
producer_hooks(module, store, monkeypatch)
if kind == "node":
result = module.build(package, node_only=True)
elif kind == "owner":
module.build(report)
result = json.loads(capsys.readouterr().out)
else:
result = module.build()
path = Path(result["artifact"])
assert path.exists() and result["sha256"] == hashlib.sha256(path.read_bytes()).hexdigest()
owner = result["retention"]["owner"]
record = store._state()["inputs"][str(path.relative_to(store.root))]
assert record["state"] == "active" and record["owner"] == owner
assert not store.plan()["errors"] and not list(path.parent.glob(".retention-*"))
def test_late_legacy_adoption_does_not_make_an_old_input_newest(store):
old = make(store, 0, managed=False)
os.utime(store.root / old, ns=(1_000_000_000, 1_000_000_000))
for i in range(1, 4):
make(store, i)
store.adopt(old, pin="review", reason="legacy record")
store.pin(old, pin="review", reason="confirmed obsolete intermediate", remove=True)
assert actions(store)[old] == "delete"
+111
View File
@@ -0,0 +1,111 @@
import hashlib
from types import SimpleNamespace
import pytest
from k1link import cache_budget as budget
def test_quota_preserves_unknown_existing_and_counts_pending_files(tmp_path):
root = tmp_path / "cache"
root.mkdir()
(root / "unknown-result").write_bytes(b"evidence")
(root / ".ongoing.tmp").write_bytes(b"x" * 4)
with (
pytest.raises(budget.CacheCapacityError),
budget.cache_publication(root, 5, limit=16, reserve=0),
):
pytest.fail("admitted over quota")
assert (root / "unknown-result").read_bytes() == b"evidence"
assert (root / ".ongoing.tmp").read_bytes() == b"x" * 4
with budget.cache_publication(root, 4, limit=16, reserve=0):
(root / "new").write_bytes(b"y" * 4)
assert budget.usage(root) == (16, 3)
with pytest.raises(budget.CacheCapacityError):
budget.require_cache_room(root, 1, limit=16, reserve=0)
def test_quota_free_reserve_and_unsafe_paths(tmp_path, monkeypatch):
monkeypatch.setattr(budget.shutil, "disk_usage", lambda _: SimpleNamespace(free=10))
with pytest.raises(budget.CacheCapacityError):
budget.require_cache_room(tmp_path / "cache", 1, limit=100, reserve=10)
root = tmp_path / "unsafe"
root.mkdir()
outside = tmp_path / "source"
outside.write_text("keep")
(root / "data").symlink_to(outside)
with pytest.raises(budget.CacheCapacityError):
budget.require_cache_room(root, 0, limit=100, reserve=0)
assert outside.read_text() == "keep"
def test_quota_serializes_process_publications(tmp_path):
import subprocess
import sys
script = """from pathlib import Path
from k1link.cache_budget import cache_publication,CacheCapacityError
import sys,time
try:
with cache_publication(Path(sys.argv[1]),6,limit=10,reserve=0):
time.sleep(.1)
(Path(sys.argv[1])/sys.argv[2]).write_bytes(b"123456")
except CacheCapacityError:sys.exit(2)
"""
commands = [[sys.executable, "-c", script, str(tmp_path), str(i)] for i in range(2)]
children = [subprocess.Popen(c) for c in commands]
assert sorted(p.wait(timeout=10) for p in children) == [0, 2]
assert budget.usage(tmp_path)[0] == 6
def test_editor_reserves_full_pending_transfers_and_keeps_ready_on_quota(tmp_path, monkeypatch):
from k1link.simulation.ai_polygon.editor_cache import EditorCache
worlds = {
str(i): {
"world_id": str(i),
"sha256": str(i) * 64,
"status": "available",
"settings": {"prepared": True},
}
for i in (1, 2)
}
cache = EditorCache(tmp_path, SimpleNamespace(get=lambda key: worlds[key]))
rows = [cache.request(str(i)) for i in (1, 2)]
payload = b"a" * 8
files = {
n: {"byte_length": len(payload), "sha256": hashlib.sha256(payload).hexdigest()}
for n in ("scene.sog", "collision.glb")
}
before = budget.usage(cache.root)[0]
monkeypatch.setitem(budget.LIMITS, "editor-cache", before + 65536 + 30)
cache.update(rows[0]["key"], {"action": "manifest", "files": files})
# Second transfer cannot consume bytes already promised to the first.
with pytest.raises(budget.CacheCapacityError):
cache.update(rows[1]["key"], {"action": "manifest", "files": files})
assert cache.get(rows[0]["key"])["status"] == "uploading"
assert cache.get(rows[1]["key"])["status"] == "queued"
def test_camera_cache_capacity_does_not_fail_decoded_frame(tmp_path, monkeypatch):
# Exercise the actual extraction path, replacing only immutable media decoding.
import threading
from collections import OrderedDict
from k1link.sessions.camera_frame import RecordedCameraFrame, RecordedCameraFrameService
service = RecordedCameraFrameService.__new__(RecordedCameraFrameService)
service._cache_root = tmp_path
service._coordination = threading.Condition()
service._lanes = OrderedDict()
service._max_decode_lanes = 1
segment = SimpleNamespace(sha256="f" * 64)
manifest = SimpleNamespace(
generation_sha256="g", artifact_id="a", epochs=[SimpleNamespace(segments=[segment])]
)
monkeypatch.setattr(service, "_source_manifest", lambda *a, **k: manifest)
frame = RecordedCameraFrame(b"0123456789", "image/jpeg", 1, 1, "x")
monkeypatch.setattr(service, "_decode", lambda *a: frame)
monkeypatch.setitem(budget.LIMITS, "camera-frame-cache", 5)
assert service.extract("s", 0) == frame
assert not list(tmp_path.glob("*.jpg"))
+48
View File
@@ -753,3 +753,51 @@ def test_e10_projection_keeps_only_nearest_point_per_pixel() -> None:
assert pixels.shape == (1, 2)
assert depths.tolist() == [2.0]
assert source.tolist() == [0]
def test_sealed_overlay_still_recovers_when_cache_is_over_quota(tmp_path, monkeypatch):
from k1link.cache_budget import LIMITS
roots = [tmp_path / name for name in ("jobs", "results", "lidar")]
for root in roots:
root.mkdir()
result = _write_result_descriptor(
roots[1], session_id="session-1", created_at_utc="2026-07-29T12:00:00Z"
)
cache_root = tmp_path / "cache"
cached = cache_root / "session-1" / result.name
cached.mkdir(parents=True)
output = cached / "recording-1.rrd"
payload = b"RRF2sealed-overlay"
output.write_bytes(payload)
(cached / "recording-1.rrd.cache.json").write_text(
json.dumps(
{
"schema_version": integrated_module.OVERLAY_CACHE_SCHEMA,
"renderer_version": integrated_module.OVERLAY_RENDERER_VERSION,
"result_id": result.name,
"recording_id": "recording-1",
"byte_length": len(payload),
"sha256": hashlib.sha256(payload).hexdigest(),
}
)
)
monkeypatch.setitem(LIMITS, "integrated-perception-overlays", 1)
monkeypatch.setattr(
integrated_module,
"validate_integrated_perception_result",
lambda *a, **k: pytest.fail("must reuse sealed evidence"),
)
store = IntegratedPerceptionOverlayStore(
jobs_root=roots[0],
results_root=roots[1],
lidar_packs_root=roots[2],
cache_root=cache_root,
ffmpeg_path=tmp_path / "ffmpeg",
)
result = store.materialize(
"session-1", application_id="nodedc_mission_core_recorded", recording_id="recording-1"
)
assert result.path == output.resolve()
assert output.read_bytes() == payload
assert not (cache_root / "session-1" / "admission.json").exists()
+6 -5
View File
@@ -5,6 +5,7 @@ from pathlib import Path
import pytest
from k1link.launchd_logs import service_command, service_log_path
from k1link.local_service_launchd import (
MissionCoreLaunchAgentError,
plan_mission_core_launch_agent,
@@ -46,13 +47,16 @@ def test_launch_agent_plan_disables_sync_and_enables_watchdog(tmp_path: Path) ->
)
desired = plistlib.loads(plan.desired_payload)
assert desired["ProgramArguments"] == [
assert service_command(desired) == [
str(uv_entrypoint),
"run",
"--no-sync",
"k1link",
"serve",
]
assert "k1link.rotating_process" in desired["ProgramArguments"]
assert service_log_path(desired).name == "k1link-serve-launchd.managed.log"
assert desired["StandardOutPath"] == desired["StandardErrorPath"] == "/dev/null"
assert desired["EnvironmentVariables"]["MISSIONCORE_SERVICE_WATCHDOG"] == "1"
assert desired["KeepAlive"] is True
assert desired["RunAtLoad"] is True
@@ -267,10 +271,7 @@ def test_launch_agent_migration_retains_existing_private_data_directory(
desired = plistlib.loads(plan.desired_payload)
assert plan.preserved_data_directory == configured_data_directory
assert (
desired["EnvironmentVariables"]["MISSIONCORE_DATA_DIR"]
== str(configured_data_directory)
)
assert desired["EnvironmentVariables"]["MISSIONCORE_DATA_DIR"] == str(configured_data_directory)
def test_launch_agent_migration_rejects_symlinked_data_directory(tmp_path: Path) -> None:
+133
View File
@@ -0,0 +1,133 @@
import signal
import subprocess
import sys
import time
from pathlib import Path
import pytest
from k1link.launchd_logs import bounded_launchd_output, service_command, service_log_path
from k1link.rotating_process import Journal, supervise
def retained(path, backups):
return b"".join(
p.read_bytes()
for p in [Path(f"{path}.{i}") for i in range(backups, 0, -1)] + [path]
if p.exists()
)
def test_binary_rotation_is_exact_and_bounded_across_restart(tmp_path):
p = tmp_path / "test.log"
j = Journal(p, max_bytes=7, backups=2)
j.write(bytes(range(21)))
j.close()
assert retained(p, 2) == bytes(range(21))
j = Journal(p, max_bytes=7, backups=2)
j.write(bytes(range(21, 35)))
j.close()
assert retained(p, 2) == bytes(range(14, 35))
assert all(x.stat().st_size <= 7 for x in tmp_path.glob("test.log*") if x.suffix != ".lock")
def test_journal_owns_writer_and_refuses_linked_targets(tmp_path):
p = tmp_path / "test.log"
j = Journal(p, max_bytes=4, backups=1)
with pytest.raises(BlockingIOError):
Journal(p, max_bytes=4, backups=1)
outside = tmp_path / "restore"
outside.write_bytes(b"preserve")
Path(f"{p}.1").symlink_to(outside)
j.write(b"1234")
with pytest.raises(ValueError):
j.write(b"5")
j.close()
assert outside.read_bytes() == b"preserve"
def test_child_stdout_stderr_and_exit_code(tmp_path):
p = tmp_path / "child.log"
result = supervise(
[
sys.executable,
"-c",
'import os;os.write(1,b"stdout\\x00");os.write(2,b"stderr");raise SystemExit(7)',
],
p,
max_bytes=100,
backups=2,
)
assert result == 7 and p.read_bytes() == b"stdout\x00stderr"
def test_signal_reaches_child_and_supervisor_exits(tmp_path):
path = tmp_path / "child.log"
code = (
"import signal,time,os;signal.signal(signal.SIGTERM,lambda *a:exit(0));"
'os.write(1,b"ready");time.sleep(30)'
)
proc = subprocess.Popen(
[
sys.executable,
"-m",
"k1link.rotating_process",
"--log",
str(path),
"--",
sys.executable,
"-c",
code,
]
)
try:
for _ in range(100):
if path.exists() and path.read_bytes() == b"ready":
break
time.sleep(0.02)
else:
pytest.fail("child failed to start")
proc.send_signal(signal.SIGTERM)
assert proc.wait(timeout=5) == 0
finally:
if proc.poll() is None:
proc.kill()
proc.wait()
def test_wrapping_preserves_command_environment_and_network_policy(tmp_path):
d = {
"Label": "example",
"ProgramArguments": [
"/usr/bin/ssh",
"-N",
"-R",
"127.0.0.1:18080:127.0.0.1:8000",
"mission-gpu",
],
"EnvironmentVariables": {"PRIVATE_VALUE": "not-printed"},
"StandardErrorPath": str(tmp_path / "old.log"),
"KeepAlive": True,
}
result = bounded_launchd_output(d, tmp_path)
assert service_command(result) == d["ProgramArguments"]
assert result["EnvironmentVariables"] == d["EnvironmentVariables"]
assert result["KeepAlive"] is True
assert service_log_path(result) == tmp_path / "old.managed.log"
assert result["StandardOutPath"] == result["StandardErrorPath"] == "/dev/null"
assert bounded_launchd_output(result, tmp_path) == result
assert d["StandardErrorPath"] == str(tmp_path / "old.log")
def test_existing_wrapper_cannot_restore_unbounded_launchd_output(tmp_path):
value = bounded_launchd_output(
{
"ProgramArguments": ["/usr/bin/ssh", "-N", "existing"],
"StandardErrorPath": str(tmp_path / "old.log"),
},
tmp_path,
)
value["StandardOutPath"] = value["StandardErrorPath"] = str(tmp_path / "old.log")
updated = bounded_launchd_output(value, tmp_path)
assert updated["StandardErrorPath"] == updated["StandardOutPath"] == "/dev/null"
assert updated["ProgramArguments"].count("k1link.rotating_process") == 1
+131
View File
@@ -0,0 +1,131 @@
import importlib.util
import plistlib
import sys
from pathlib import Path
import pytest
SCRIPT = Path(__file__).parents[1] / "scripts/manage_runtime_log_policy.py"
# Script imports its canonical sibling management helpers.
sys.path.insert(0, str(SCRIPT.parent))
spec = importlib.util.spec_from_file_location("runtime_log_policy", SCRIPT)
manager = importlib.util.module_from_spec(spec)
spec.loader.exec_module(manager)
def fixture(tmp_path):
root = tmp_path / "repo"
root.mkdir()
home = tmp_path / "home"
path = home / "Library/LaunchAgents/com.nodedc.mission-core.local.plist"
path.parent.mkdir(parents=True)
value = {
"Label": "com.nodedc.mission-core.local",
"ProgramArguments": ["/opt/homebrew/bin/uv", "run", "--no-sync", "k1link", "serve"],
"WorkingDirectory": str(root),
"EnvironmentVariables": {"keep": "private"},
"KeepAlive": True,
"StandardErrorPath": str(home / "Library/Logs/core.log"),
"StandardOutPath": str(home / "Library/Logs/core.log"),
}
path.write_bytes(plistlib.dumps(value))
return root, home, path
def test_plan_preserves_foreign_fields_and_apply_refuses_stale(tmp_path, monkeypatch):
root, home, path = fixture(tmp_path)
original = path.read_bytes()
plan, before, desired = manager.plan(root, "core", home=home)
assert before == original and path.read_bytes() == original
assert plistlib.loads(desired)["EnvironmentVariables"] == {"keep": "private"}
monkeypatch.setattr(Path, "home", lambda: home)
value = plistlib.loads(original)
value["KeepAlive"] = False
path.write_bytes(plistlib.dumps(value))
with pytest.raises(ValueError, match="Stale"):
manager.apply(plan)
assert plistlib.loads(path.read_bytes())["KeepAlive"] is False
def test_failed_acceptance_restores_exact_declaration(tmp_path, monkeypatch):
root, home, path = fixture(tmp_path)
plan, before, _ = manager.plan(root, "core", home=home)
monkeypatch.setattr(Path, "home", lambda: home)
calls = []
monkeypatch.setattr(manager, "_reload_launch_agent", lambda p: calls.append(p))
def acceptance(*args):
if len(calls) == 1:
raise RuntimeError("failed canary")
return {"restored": True}
monkeypatch.setattr(manager, "accept", acceptance)
with pytest.raises(RuntimeError, match="failed canary"):
manager.apply(plan)
assert path.read_bytes() == before and len(calls) == 2
assert list((root / ".runtime/storage-maintenance/log-policy").rglob("*.plist"))
def test_scanner_records_and_rotated_permissions_are_bounded(tmp_path):
import logging
import stat
from k1link.web.runtime_diagnostics import (
_EXTRA_FIELDS,
PrivateRotatingFileHandler,
ScannerDiagnosticJsonFormatter,
)
record = logging.LogRecord("test", logging.INFO, "x", 1, "x" * 100000, (), None)
for field in _EXTRA_FIELDS:
setattr(record, field, "я" * 100000)
formatter = ScannerDiagnosticJsonFormatter()
payload = formatter.format(record)
assert len(payload.encode()) <= 16384
path = tmp_path / "diagnostic.log"
handler = PrivateRotatingFileHandler(path, maxBytes=200, backupCount=2, encoding="utf-8")
handler.setFormatter(formatter)
for _ in range(4):
handler.emit(logging.LogRecord("test", logging.INFO, "x", 1, "test message", (), None))
handler.close()
assert len(list(tmp_path.iterdir())) == 3
assert all(stat.S_IMODE(p.stat().st_mode) == 0o600 for p in tmp_path.iterdir())
@pytest.mark.parametrize("exit_code", [0, 9])
def test_check_wrapper_cleans_only_its_scratch_on_success_and_failure(tmp_path, exit_code):
import check_python
root = tmp_path / "repo"
executable = root / ".venv/bin/python"
executable.parent.mkdir(parents=True)
executable.write_text(
f"#!{sys.executable}\n"
"import os,pathlib,sys\n"
"p=pathlib.Path(os.environ['MYPY_CACHE_DIR']);p.mkdir(parents=True);(p/'data').write_bytes(b'cache')\n"
"assert os.environ['RUFF_NO_CACHE']=='true'\n"
"assert os.environ['PYTHONDONTWRITEBYTECODE']=='1'\n"
f"sys.exit({exit_code})\n"
)
executable.chmod(0o700)
protected = root / ".runtime/python-checks/another-job"
protected.mkdir(parents=True)
(protected / "keep").write_text("active")
assert check_python.run("mypy", [], root=root) == exit_code
assert [p for p in protected.parent.iterdir() if p.is_dir()] == [protected]
assert (protected / "keep").read_text() == "active"
def test_check_wrapper_refuses_accumulated_crash_directories_without_removing_them(tmp_path):
import check_python
root = tmp_path / "repo"
parent = root / ".runtime/python-checks"
for i in range(4):
p = parent / str(i)
p.mkdir(parents=True)
(p / "keep").write_bytes(b"preserve")
with pytest.raises(ValueError, match="Four active"):
check_python.run("mypy", [], root=root)
assert len(list(parent.glob("*/keep"))) == 4