214 lines
8.2 KiB
Python
214 lines
8.2 KiB
Python
import hashlib
|
|
import json
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from k1link.laboratory.local_presentations import LocalPresentations
|
|
from k1link.laboratory.replay_publication import ReplayManifest, ReplayPublications
|
|
from k1link.laboratory.replay_restore import WorkerReplayRestore
|
|
from k1link.laboratory.worker_gateway import LaboratoryGatewayConfiguration
|
|
from k1link.web.worker_ready_replays import build_ready_replay_router
|
|
|
|
ID = "ai-layer-ddrnet-" + "a" * 64
|
|
BASE = "b" * 64
|
|
KEY = "c" * 64
|
|
PAYLOAD = b"RRF2" + bytes(range(256)) * 8192
|
|
|
|
|
|
def manifest(payload=PAYLOAD):
|
|
return ReplayManifest(
|
|
schema_version="missioncore.ready-lab-replay/v1",
|
|
result_id=ID,
|
|
base_sha256=BASE,
|
|
cache_key=KEY,
|
|
sha256=hashlib.sha256(payload).hexdigest(),
|
|
byte_length=len(payload),
|
|
)
|
|
|
|
|
|
def restore(tmp_path, handler):
|
|
token = tmp_path / "token"
|
|
token.write_text("a" * 64)
|
|
return WorkerReplayRestore(
|
|
LaboratoryGatewayConfiguration("http://localhost", token),
|
|
transport=httpx.MockTransport(handler),
|
|
)
|
|
|
|
|
|
class Interrupted(httpx.SyncByteStream):
|
|
def __iter__(self):
|
|
yield PAYLOAD[: 1024**2]
|
|
raise httpx.ReadError("network interrupted")
|
|
|
|
|
|
def response(payload, doc, offset=0):
|
|
headers = {"etag": f'"{doc.sha256}"', "content-length": str(len(payload))}
|
|
if offset:
|
|
headers["content-range"] = f"bytes {offset}-{doc.byte_length - 1}/{doc.byte_length}"
|
|
return httpx.Response(206 if offset else 200, headers=headers, stream=httpx.ByteStream(payload))
|
|
|
|
|
|
def test_cold_transfer_resumes_and_seals_verified_copy(tmp_path):
|
|
doc = manifest()
|
|
calls = []
|
|
|
|
def handler(request):
|
|
calls.append(request)
|
|
if not request.url.path.endswith(".rrd"):
|
|
return httpx.Response(200, json=doc.model_dump())
|
|
if len(calls) == 2:
|
|
return httpx.Response(
|
|
200,
|
|
headers={"etag": f'"{doc.sha256}"', "content-length": str(doc.byte_length)},
|
|
stream=Interrupted(),
|
|
)
|
|
assert request.headers["range"] == f"bytes={1024**2}-"
|
|
assert request.headers["if-range"] == f'"{doc.sha256}"'
|
|
return response(PAYLOAD[1024**2 :], doc, 1024**2)
|
|
|
|
cache = tmp_path / "observatory-portable-replay-cache"
|
|
result = restore(tmp_path, handler).restore(ID, BASE, KEY, cache)
|
|
assert result.path.read_bytes() == PAYLOAD
|
|
assert json.loads((cache / (KEY + ".json")).read_text())["sha256"] == doc.sha256
|
|
assert not list(cache.glob("*.part"))
|
|
assert len(calls) == 3
|
|
|
|
|
|
@pytest.mark.parametrize("error", ["hash", "etag", "length", "identity", "redirect", "unavailable"])
|
|
def test_bad_remote_never_publishes_or_falls_back(tmp_path, error):
|
|
doc = manifest()
|
|
|
|
def handler(request):
|
|
if not request.url.path.endswith(".rrd"):
|
|
value = doc.model_dump()
|
|
if error == "identity":
|
|
value["cache_key"] = "d" * 64
|
|
if error == "redirect":
|
|
return httpx.Response(302, headers={"location": "https://untrusted.invalid/"})
|
|
if error == "unavailable":
|
|
return httpx.Response(503)
|
|
return httpx.Response(200, json=value)
|
|
content = b"RRF2" + b"x" * (len(PAYLOAD) - 4) if error == "hash" else PAYLOAD
|
|
answer = response(content, doc)
|
|
if error == "etag":
|
|
answer.headers["etag"] = '"wrong"'
|
|
if error == "length":
|
|
answer.headers["content-length"] = "42"
|
|
return answer
|
|
|
|
cache = tmp_path / "observatory-portable-replay-cache"
|
|
with pytest.raises((ValueError, httpx.HTTPError)):
|
|
restore(tmp_path, handler).restore(ID, BASE, KEY, cache)
|
|
assert not list(cache.glob("*.rrd"))
|
|
assert not list(cache.glob("*.json"))
|
|
assert not list(cache.glob("*.part"))
|
|
|
|
|
|
def test_legacy_missing_publication_is_explicit(tmp_path):
|
|
service = restore(tmp_path, lambda _: httpx.Response(404))
|
|
assert service.restore(ID, BASE, KEY, tmp_path / "observatory-portable-replay-cache") is None
|
|
|
|
|
|
def test_worker_publication_immutable_range_and_generation(tmp_path):
|
|
source = tmp_path / "source.rrd"
|
|
source.write_bytes(PAYLOAD)
|
|
store = ReplayPublications(tmp_path)
|
|
doc = manifest()
|
|
store.publish(doc, source)
|
|
app = FastAPI()
|
|
app.include_router(build_ready_replay_router(store))
|
|
client = TestClient(app)
|
|
prefix = f"/api/v1/laboratory/portable-replays/{ID}/{BASE}"
|
|
assert client.get(prefix).json() == doc.model_dump()
|
|
assert client.get(prefix + "/recording.rrd?generation=" + "e" * 64).status_code == 412
|
|
answer = client.get(
|
|
prefix + "/recording.rrd?generation=" + doc.sha256,
|
|
headers={"Range": "bytes=4-15", "If-Range": f'"{doc.sha256}"'},
|
|
)
|
|
assert answer.status_code == 206 and answer.content == PAYLOAD[4:16]
|
|
assert store.active[ID] == 0
|
|
with pytest.raises(ValueError, match="immutable"):
|
|
store.publish(manifest(b"RRF2different"), source)
|
|
store.publish(doc, source) # Exact retry is idempotent.
|
|
(tmp_path / "state/data-ownership/receipts").mkdir(parents=True)
|
|
(tmp_path / "state/data-ownership/receipts" / (ID + ".json")).write_text("{}")
|
|
assert client.get(prefix).status_code == 409
|
|
|
|
|
|
def test_cache_override_keeps_working_copies_and_deletion_block(tmp_path):
|
|
original = LocalPresentations(tmp_path)
|
|
original.policy(30)
|
|
before = original.index.read_bytes()
|
|
scratch = LocalPresentations(tmp_path, cache_data_dir=tmp_path / "scratch")
|
|
assert scratch.snapshot()["entries"] == {}
|
|
scratch.policy(7)
|
|
assert original.index.read_bytes() == before
|
|
blocked = tmp_path / "lab-deletions/blocked" / (ID + ".json")
|
|
blocked.parent.mkdir(parents=True)
|
|
blocked.write_text("{}")
|
|
with pytest.raises(ValueError):
|
|
scratch.acquire(ID)
|
|
|
|
|
|
def test_missing_published_payload_is_not_legacy_absence(tmp_path):
|
|
source = tmp_path / "source.rrd"
|
|
source.write_bytes(PAYLOAD)
|
|
store = ReplayPublications(tmp_path)
|
|
doc = manifest()
|
|
store.publish(doc, source)
|
|
app = FastAPI()
|
|
app.include_router(build_ready_replay_router(store))
|
|
client = TestClient(app)
|
|
(store.directory(ID, BASE) / (doc.sha256 + ".rrd")).unlink()
|
|
assert client.get(f"/api/v1/laboratory/portable-replays/{ID}/{BASE}").status_code == 409
|
|
|
|
|
|
def test_published_composition_is_owned_and_deleted_without_source(tmp_path):
|
|
from k1link.laboratory.data_deletion import OwnedLabData
|
|
from k1link.laboratory.deletion_inventory import inventory_worker
|
|
roots = {name: tmp_path / name for name in ("lab", "archive", "ai", "tgs")}
|
|
for path in roots.values():
|
|
path.mkdir()
|
|
source = tmp_path / "source.rrd"
|
|
source.write_bytes(PAYLOAD)
|
|
store = ReplayPublications(roots["lab"])
|
|
doc = manifest().model_copy(update={"result_id": "ai-composition-" + "d" * 64})
|
|
store.publish(doc, source)
|
|
(roots["archive"] / "catalog.json").write_text(
|
|
'{"schema_version":"missioncore.laboratory-archive-catalog/v1","groups":[]}'
|
|
)
|
|
owned = OwnedLabData(roots["lab"] / "state/data-ownership", roots)
|
|
inventory_worker(owned, [doc.result_id])
|
|
owned.delete([doc.result_id])
|
|
assert not (store.directory(doc.result_id, BASE) / "manifest.json").exists()
|
|
assert source.read_bytes() == PAYLOAD
|
|
|
|
|
|
def test_composition_deletion_includes_ready_product_but_keeps_shared_jobs(tmp_path):
|
|
from types import SimpleNamespace
|
|
|
|
from k1link.laboratory.deletion_coordinator import LabDeletionCoordinator
|
|
|
|
selected = SimpleNamespace(run_id="ai-composition-" + "d" * 64, job_ids=["shared", "own"])
|
|
retained = SimpleNamespace(run_id="ai-composition-" + "e" * 64, job_ids=["shared"])
|
|
jobs = {
|
|
key: SimpleNamespace(job_id=key, state="succeeded", result_id=key + "-result")
|
|
for key in ("shared", "own")
|
|
}
|
|
coordinator = LabDeletionCoordinator(
|
|
store=SimpleNamespace(data_dir=tmp_path),
|
|
queue=SimpleNamespace(get=jobs.__getitem__),
|
|
compositions=SimpleNamespace(
|
|
get=lambda _: selected, list=lambda **_: [selected, retained]
|
|
),
|
|
copies=None,
|
|
gateway=None,
|
|
)
|
|
plan = coordinator._plan("composition", selected.run_id)
|
|
assert plan["owners"] == [selected.run_id, "own", "own-result"]
|
|
assert plan["jobs"] == ["own"]
|
|
assert plan["sessions"] == ["own-result"]
|