Bound semantic worker storage and add verified evidence closeout
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"compact", Path(__file__).parents[1] / "scripts/compact_closed_evidence.py"
|
||||
)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
|
||||
def fixture(tmp_path, monkeypatch):
|
||||
root = tmp_path / "closed"
|
||||
root.mkdir()
|
||||
store = tmp_path / "cas"
|
||||
for name in ["first.npz", "second.npz"]:
|
||||
(root / name).write_bytes(b"abcd" * 20000)
|
||||
(root / "original.ply").write_bytes(b"abcd" * 20000)
|
||||
monkeypatch.setattr(m.shutil, "disk_usage", lambda p: SimpleNamespace(free=1000 * 1024**3))
|
||||
return root, store
|
||||
|
||||
|
||||
def test_aliases_preserve_bytes_and_restore_independent_copy(tmp_path, monkeypatch):
|
||||
root, store = fixture(tmp_path, monkeypatch)
|
||||
plan = m.plan([root], store)
|
||||
assert plan["duplicate_bytes"] == 80000
|
||||
m.apply(plan)
|
||||
first, second = root / "first.npz", root / "second.npz"
|
||||
assert first.samefile(second) and first.read_bytes() == b"abcd" * 20000
|
||||
assert not (root / "original.ply").samefile(first)
|
||||
row = next(x for x in plan["groups"][0] if x["path"] == str(first))
|
||||
blob = next(store.glob("*.blob"))
|
||||
restored = m.restore_alias(row, blob, tmp_path / "restored.npz")
|
||||
assert not restored.samefile(second)
|
||||
assert first.samefile(second)
|
||||
restored.write_bytes(b"changed")
|
||||
assert second.read_bytes() == b"abcd" * 20000
|
||||
|
||||
|
||||
def test_changed_candidate_refuses_group_before_replacement(tmp_path, monkeypatch):
|
||||
root, store = fixture(tmp_path, monkeypatch)
|
||||
plan = m.plan([root], store)
|
||||
(root / "second.npz").write_bytes(b"changed")
|
||||
with pytest.raises(ValueError, match="changed"):
|
||||
m.apply(plan)
|
||||
assert (root / "first.npz").stat().st_nlink == 1
|
||||
assert (root / "second.npz").read_bytes() == b"changed"
|
||||
|
||||
|
||||
def test_restore_refuses_permissions_drift(tmp_path, monkeypatch):
|
||||
root, store = fixture(tmp_path, monkeypatch)
|
||||
document = m.plan([root], store)
|
||||
m.apply(document)
|
||||
blob = next(store.glob("*.blob"))
|
||||
blob.chmod(0o600)
|
||||
with pytest.raises(ValueError, match="matches"):
|
||||
m.restore_alias(document["groups"][0][0], blob, tmp_path / "restored")
|
||||
assert not (tmp_path / "restored").exists()
|
||||
@@ -0,0 +1,163 @@
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"evidence_closeout", Path(__file__).parents[1] / "simulation/ai-polygon/evidence_closeout.py"
|
||||
)
|
||||
evidence = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(evidence)
|
||||
|
||||
|
||||
def setup(tmp_path):
|
||||
job, store = tmp_path / "job", tmp_path / "archives"
|
||||
job.mkdir()
|
||||
(job / "urban-map.json").write_text('{"features":[]}')
|
||||
(job / "observations.bin").write_bytes(b"preserved observations" * 1000)
|
||||
return job, store
|
||||
|
||||
|
||||
def test_lossless_closeout_keeps_map_and_restores_exact_source(tmp_path):
|
||||
job, store = setup(tmp_path)
|
||||
original = (job / "observations.bin").read_bytes()
|
||||
result = evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||
assert result["phase"] == "complete"
|
||||
assert (job / "urban-map.json").exists()
|
||||
assert not (job / "observations.bin").exists()
|
||||
target = tmp_path / "restored.bin"
|
||||
evidence.restore_file(store / "job-1/closeout.json", "observations.bin", target)
|
||||
assert target.read_bytes() == original
|
||||
assert evidence.closeout(job, store, "job-1", reserve=0) == result
|
||||
|
||||
|
||||
def test_capacity_refusal_preserves_every_input(tmp_path):
|
||||
job, store = setup(tmp_path)
|
||||
with pytest.raises(RuntimeError, match="quota"):
|
||||
evidence.closeout(job, store, "job-1", limit=10, reserve=0)
|
||||
assert (job / "observations.bin").exists()
|
||||
assert not (store / "job-1/evidence.zip").exists()
|
||||
|
||||
|
||||
def test_link_and_pin_refused_without_removal(tmp_path):
|
||||
job, store = setup(tmp_path)
|
||||
(job / "RETAIN.json").write_text("{}")
|
||||
with pytest.raises(ValueError, match="pinned"):
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
(job / "RETAIN.json").unlink()
|
||||
(job / "linked").symlink_to(tmp_path / "elsewhere")
|
||||
with pytest.raises((ValueError, FileNotFoundError)):
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
assert (job / "observations.bin").exists()
|
||||
|
||||
|
||||
def test_crash_after_unlink_reconciles_only_journaled_path(tmp_path, monkeypatch):
|
||||
job, store = setup(tmp_path)
|
||||
original = Path.unlink
|
||||
|
||||
def interrupted(path, *args, **kwargs):
|
||||
original(path, *args, **kwargs)
|
||||
if path == job / "observations.bin":
|
||||
raise OSError("lost acknowledgement")
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", interrupted)
|
||||
with pytest.raises(OSError):
|
||||
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||
monkeypatch.setattr(Path, "unlink", original)
|
||||
assert evidence.closeout(job, store, "job-1", reserve=0)["phase"] == "complete"
|
||||
|
||||
|
||||
def test_changed_source_and_corrupt_archive_are_preserved(tmp_path, monkeypatch):
|
||||
job, store = setup(tmp_path)
|
||||
original = Path.unlink
|
||||
|
||||
def interrupted(path, *args, **kwargs):
|
||||
if path == job / "observations.bin":
|
||||
raise OSError("interrupted")
|
||||
return original(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", interrupted)
|
||||
with pytest.raises(OSError):
|
||||
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||
monkeypatch.setattr(Path, "unlink", original)
|
||||
(job / "observations.bin").write_bytes(b"new evidence")
|
||||
with pytest.raises(ValueError, match="changed after"):
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
assert (job / "observations.bin").read_bytes() == b"new evidence"
|
||||
(store / "job-1/evidence.zip").write_bytes(b"broken")
|
||||
with pytest.raises(ValueError, match="checksum"):
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
assert (job / "observations.bin").exists()
|
||||
|
||||
|
||||
def test_root_link_and_control_link_are_rejected(tmp_path):
|
||||
job, store = setup(tmp_path)
|
||||
link = tmp_path / "job-alias"
|
||||
link.symlink_to(job, target_is_directory=True)
|
||||
with pytest.raises(ValueError, match="Linked"):
|
||||
evidence.closeout(link, store, "job-1", reserve=0)
|
||||
store.mkdir(exist_ok=True)
|
||||
(store / "job-1").symlink_to(job, target_is_directory=True)
|
||||
with pytest.raises(ValueError, match="Linked"):
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
assert (job / "observations.bin").exists()
|
||||
|
||||
|
||||
def test_resume_honors_new_pin_and_capacity(tmp_path, monkeypatch):
|
||||
job, store = setup(tmp_path)
|
||||
original = evidence.zipfile.ZipFile
|
||||
monkeypatch.setattr(
|
||||
evidence.zipfile, "ZipFile", lambda *a, **kw: (_ for _ in ()).throw(OSError("interrupt"))
|
||||
)
|
||||
with pytest.raises(OSError):
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
monkeypatch.setattr(evidence.zipfile, "ZipFile", original)
|
||||
with pytest.raises(RuntimeError, match="quota"):
|
||||
evidence.closeout(job, store, "job-1", limit=1, reserve=0)
|
||||
(job / "RETAIN.json").write_text("{}")
|
||||
with pytest.raises(ValueError, match="pinned"):
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
assert (job / "observations.bin").exists()
|
||||
|
||||
|
||||
def test_complete_retry_repairs_missing_archive_locator(tmp_path):
|
||||
job, store = setup(tmp_path)
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
(job / "ARCHIVED.json").unlink()
|
||||
evidence.closeout(job, store, "job-1", reserve=0)
|
||||
assert json.loads((job / "ARCHIVED.json").read_text())["owner"] == "job-1"
|
||||
|
||||
|
||||
def test_partial_final_journal_record_is_recovered(tmp_path, monkeypatch):
|
||||
job, store = setup(tmp_path)
|
||||
original = Path.unlink
|
||||
|
||||
def interrupted(path, *args, **kw):
|
||||
original(path, *args, **kw)
|
||||
if path == job / "observations.bin":
|
||||
raise OSError("crash")
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", interrupted)
|
||||
with pytest.raises(OSError):
|
||||
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||
monkeypatch.setattr(Path, "unlink", original)
|
||||
with (store / "job-1/deletions.jsonl").open("ab") as f:
|
||||
f.write(b'{"action":"rem')
|
||||
assert evidence.closeout(job, store, "job-1", reserve=0)["phase"] == "complete"
|
||||
|
||||
|
||||
def test_published_archive_before_state_commit_resumes_without_second_budget(tmp_path, monkeypatch):
|
||||
job, store = setup(tmp_path)
|
||||
original = evidence.atomic_json
|
||||
|
||||
def interrupted(path, value):
|
||||
if path.name == "closeout.json" and value.get("phase") == "archived":
|
||||
raise OSError("crash after zip publish")
|
||||
return original(path, value)
|
||||
|
||||
monkeypatch.setattr(evidence, "atomic_json", interrupted)
|
||||
with pytest.raises(OSError):
|
||||
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||
monkeypatch.setattr(evidence, "atomic_json", original)
|
||||
assert evidence.closeout(job, store, "job-1", limit=1, reserve=0)["phase"] == "complete"
|
||||
@@ -246,3 +246,33 @@ def test_source_read_retries_transport_only(preparer):
|
||||
"source": "verified"
|
||||
}
|
||||
assert len(calls) == 5
|
||||
|
||||
|
||||
def test_closeout_failure_retains_released_marker_until_retry(preparer, monkeypatch, tmp_path):
|
||||
marker, output = outbox(preparer, monkeypatch, tmp_path)
|
||||
record = preparer.read_json(marker)
|
||||
record["retention"] = dict(
|
||||
root=str(output), archive_root=str(tmp_path / "archives"), archive_limit=1024**3, reserve=0
|
||||
)
|
||||
preparer.write_json(marker, record)
|
||||
actions = []
|
||||
|
||||
class Client:
|
||||
def request(self, path, body):
|
||||
actions.append(body["action"])
|
||||
return {}
|
||||
|
||||
close = preparer.closeout
|
||||
monkeypatch.setattr(
|
||||
preparer, "closeout", lambda *a, **kw: (_ for _ in ()).throw(OSError("archive unavailable"))
|
||||
)
|
||||
with pytest.raises(OSError):
|
||||
preparer.reconcile(Client(), marker)
|
||||
assert preparer.read_json(marker)["released"] is True
|
||||
assert (output / "urban-map.json").exists()
|
||||
monkeypatch.setattr(preparer, "closeout", close)
|
||||
preparer.reconcile(Client(), marker)
|
||||
assert actions == ["complete", "release"]
|
||||
assert not marker.exists()
|
||||
assert (output / "urban-map.json").exists()
|
||||
assert (output / "ARCHIVED.json").exists()
|
||||
|
||||
@@ -168,3 +168,19 @@ def test_complete_collection_receipt_keeps_identity_and_terminal_invariants(tmp_
|
||||
assert edits.get(world)["learning"]["state"] == "draft-ready"
|
||||
with pytest.raises(RuntimeError):
|
||||
edits.receipt(world, saved["revision"], {**receipt, "sample_count": 212})
|
||||
|
||||
|
||||
def test_research_and_dataset_budgets_are_separate_and_bounded(tmp_path):
|
||||
worker = ds.Store(tmp_path / "worker", quota=65536, reserve=0, research_quota=1024)
|
||||
(worker.root / "experiments").mkdir()
|
||||
(worker.root / "experiments/history.bin").write_bytes(b"x" * 1024)
|
||||
worker.capacity(0)
|
||||
(worker.root / "experiments/history.bin").write_bytes(b"x" * 1025)
|
||||
with pytest.raises(RuntimeError, match="research storage"):
|
||||
worker.capacity(0)
|
||||
(worker.root / "experiments/history.bin").unlink()
|
||||
(worker.root / "unknown-new-directory").mkdir()
|
||||
(worker.root / "unknown-new-directory/data.bin").write_bytes(b"x" * 65536)
|
||||
with pytest.raises(RuntimeError, match="learning storage"):
|
||||
worker.capacity(0)
|
||||
worker.db.close()
|
||||
|
||||
@@ -62,3 +62,37 @@ def test_corrupted_predecessor_refuses_before_staging(tmp_path):
|
||||
def test_escape_rejected(tmp_path, path):
|
||||
with pytest.raises(ValueError):
|
||||
module.confined(tmp_path, path)
|
||||
|
||||
|
||||
def test_learning_patch_keeps_image_and_unrelated_payload(tmp_path):
|
||||
before = {
|
||||
"dataset_store.py": hashlib.sha256(b"old").hexdigest(),
|
||||
"templates.json": hashlib.sha256(b"templates").hexdigest(),
|
||||
}
|
||||
identity = hashlib.sha256(json.dumps(before, sort_keys=True).encode()).hexdigest()
|
||||
base = tmp_path / "releases" / ("semantic-learning-" + identity[:16])
|
||||
base.mkdir(parents=True)
|
||||
(base / "dataset_store.py").write_bytes(b"old")
|
||||
(base / "templates.json").write_bytes(b"templates")
|
||||
manifest = {"id": identity, "files": before, "image": "pinned-image", "schema_version": "v1"}
|
||||
encoded = json.dumps(manifest).encode()
|
||||
(base / "release.json").write_bytes(encoded)
|
||||
recipe = dict(
|
||||
kind="semantic-learning",
|
||||
base_release=identity[:16],
|
||||
base_manifest_sha256=hashlib.sha256(encoded).hexdigest(),
|
||||
overlays={
|
||||
"dataset_store.py": dict(
|
||||
base64=base64.b64encode(b"new").decode(), sha256=hashlib.sha256(b"new").hexdigest()
|
||||
)
|
||||
},
|
||||
)
|
||||
result = module.stage(tmp_path, recipe)
|
||||
target = tmp_path / "releases" / ("semantic-learning-" + result["release"])
|
||||
after = json.loads((target / "release.json").read_text())
|
||||
assert (
|
||||
after["image"] == "pinned-image"
|
||||
and after["files"]["templates.json"] == before["templates.json"]
|
||||
)
|
||||
assert (base / "dataset_store.py").read_bytes() == b"old"
|
||||
assert (target / "dataset_store.py").read_bytes() == b"new"
|
||||
|
||||
Reference in New Issue
Block a user