Files
NODEDC_MISSION_CORE/tests/test_build_retention.py
T

510 lines
21 KiB
Python

"""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", "node-archived"])
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",
"tests/test_media_reconfiguration.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",
"apps/node-agent/packaging/k1_maintenance.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)
write('scripts/packaging/qualified_payloads.py')
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": []})
vendor = write("apps/node-agent/build/netbird/netbird-fixture.tar.gz")
document("src/k1link/fleet/netbird/clients.lock.json", {"items": [{
"id": "linux-amd64", "filename": vendor.name, "bytes": vendor.stat().st_size,
"sha256": hashlib.sha256(vendor.read_bytes()).hexdigest(),
}]})
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},
)
if kind == 'node-archived':
from qualified_payloads import QualifiedPayloads
qualification = store.root / 'x4-qualified'
qualification.mkdir()
package = qualification / package.name
package.write_bytes(b'fixture')
report_bytes = b'{"version":"0.1.0","revision":1}'
(qualification / 'package-result.json').write_bytes(report_bytes)
archive_root = xroot / 'build'
archive_root.mkdir(parents=True, exist_ok=True)
payloads = QualifiedPayloads(qualification, archive_root, store.root)
monkeypatch.setattr('qualified_payloads.open_files', lambda paths: None)
with payloads.locked():
artifact = archive_root / ('mission-core-x4-install-' + 'b' * 24 + '.pyz')
published = payloads.publish(artifact, {package.name: b'fixture'})
payloads.register(published, {package.name: b'fixture'},
'package-result.json', report_bytes)
assert payloads.closeout()['state'] == 'complete'
assert not package.exists()
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 in ("node", "node-archived"):
(xroot / 'build').mkdir(parents=True, exist_ok=True)
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-*"))
if kind == 'node-archived':
with zipfile.ZipFile(path) as archive:
member = 'source/' + store.root.name + '/apps/node-agent/build/model-packages/'
assert archive.read(member + package.name) == b'fixture'
assert not package.exists()
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"