Files
NODEDC_MISSION_CORE/tests/test_infrastructure_jobs.py
DCCONSTRUCTIONS f48411f8fe feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
2026-10-29 09:10:01 +03:00

302 lines
12 KiB
Python

"""Admission, restart and zero-copy inputs for full-location mapping."""
import importlib.util
import json
from pathlib import Path
import pytest
from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs
ROOT = Path(__file__).resolve().parents[1]
def world():
return dict(
world_id="aiworld-" + "a" * 32,
sha256="b" * 64,
collider_sha256="c" * 64,
local_scene=dict(visual_rotation=[0, 0, 0], collision_rotation=[0, 0, 0]),
)
def test_idempotency_owner_and_restart_do_not_release_early(tmp_path):
store = InfrastructureJobs(tmp_path)
row = store.request(world())
key = row["key"]
assert store.request(world()) == row
store.claim(key, "owner")
with pytest.raises(RuntimeError):
store.claim(key, "other")
store.update(key, dict(action="fail"), "owner")
assert store.pending()["key"] == key
assert store.request(world())["status"] == "failed"
with pytest.raises(RuntimeError):
store.update(key, dict(action="release"), "other")
store.update(key, dict(action="release", previous_owner="owner"), "restarted-worker")
assert store.pending() is None
assert store.request(world())["status"] == "queued"
def test_completed_map_still_holds_gpu_until_cleanup(tmp_path):
store = InfrastructureJobs(tmp_path)
key = store.request(world())["key"]
store.claim(key, "owner")
store.update(key, dict(action="complete", result={"sha256": "d" * 64}), "owner")
assert store.pending()["status"] == "ready"
assert store.request(world())["status"] == "ready"
store.update(key, dict(action="release"), "owner")
assert store.pending() is None
changed = world()
changed["collider_sha256"] = "e" * 64
assert store.current(changed) is None
def test_invalid_progress_and_old_provider(tmp_path, monkeypatch):
store = InfrastructureJobs(tmp_path)
key = store.request(world())["key"]
store.claim(key, "owner")
for body in [
dict(phase="copy-source", completed=0, total=10),
dict(phase="survey", completed=11, total=10),
]:
with pytest.raises(ValueError):
store.update(key, dict(action="progress", **body), "owner")
store.update(key, dict(action="release"), "owner")
store.request(world())
monkeypatch.setattr(
"k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64
)
assert store.pending() is None
assert store.current(world()) is None
assert store.request(world())["key"] != key
def sources():
spec = importlib.util.spec_from_file_location(
"infrastructure_sources", ROOT / "simulation/ai-polygon/infrastructure_sources.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_existing_files_reused_without_writing_or_copying(tmp_path):
module = sources()
w = world()
root = tmp_path / "project-packages" / w["sha256"]
root.mkdir(parents=True)
collider = root / (w["collider_sha256"] + ".decoded.glb")
collider.write_bytes(b"fixture collider")
collider.with_suffix(".json").write_text(
json.dumps(dict(source_sha256=w["collider_sha256"], sha256=module.checksum(collider)))
)
source = root / "existing.ply"
source.write_bytes(b"fixture complete ply")
source.with_suffix(".json").write_text(
json.dumps(
dict(
source_sha256=w["sha256"],
sha256=module.checksum(source),
coverage="complete-source",
spatially_cropped=False,
lod=1,
)
)
)
(root / "terrain.json").write_text(
json.dumps(
dict(
source_sha256=w["sha256"],
source_collider_sha256=w["collider_sha256"],
collision_rotation=[0, 0, 0],
)
)
)
before = {str(p): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()}
resolved, descriptor = module.resolve_sources(w, tmp_path)
assert (
resolved == root
and descriptor["ply"] == source.name
and descriptor["sha256"] == module.checksum(source)
)
assert {str(p): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} == before
source.write_bytes(b"changed")
with pytest.raises(ValueError, match="changed"):
module.resolve_sources(w, tmp_path)
def test_absent_scene_does_not_create_a_cache(tmp_path):
with pytest.raises(ValueError, match="prepared shared scene"):
sources().resolve_sources(world(), tmp_path)
assert not list(tmp_path.iterdir())
@pytest.mark.parametrize("resources,cpus,memory", [(None,"4","16g"), ({"cpus":8,"memory_gib":24},"8","24g")])
def test_container_preserves_image_pythonpath_and_shared_readonly_mount(tmp_path, monkeypatch, resources, cpus, memory):
from types import SimpleNamespace
monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon"))
import infrastructure_containers as containers
marker = tmp_path / "active.json"
marker.write_text(json.dumps(dict(key="a" * 64, containers=[])))
commands = []
def docker(*args, **kwargs):
commands.append(args)
output = (
json.dumps([{"Config": {"Env": ["PYTHONPATH=/vendor/python"]}}])
if args[:2] == ("image", "inspect")
else "container-id"
)
return SimpleNamespace(stdout=output, stderr="", returncode=0)
states = iter(
[
None,
{"Id": "container-id"},
{"Id": "container-id", "State": {"Running": False, "ExitCode": 0}},
]
)
monkeypatch.setattr(containers, "docker", docker)
def inspect(name, key):
assert name == "ndc-infrastructure-" + "a" * 16 + "-survey"
assert key == "a" * 64
return next(states)
monkeypatch.setattr(containers, "inspect_owned", inspect)
monkeypatch.setattr(containers, "cleanup", lambda *args: None)
source = tmp_path / "existing-source"
containers.run_container(
marker,
"survey",
"pinned-image",
[(source, "/input", True)],
["/app/whole_scene.py"],
tmp_path,
lambda: None,
10,
environment={"PYTHONPATH": "/candidate", "OMP_NUM_THREADS": "2"},
volumes=[("ndc-test-cache", "/cache")],
readonly=True,
resources=resources,
)
create = next(c for c in commands if c[0] == "create")
assert (
"PYTHONPATH=/geometry:/app:/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e:/vendor/python"
in create
)
assert "type=bind,source=" + str(source.resolve()) + ",target=/input,readonly" in create
assert create[create.index("--network") + 1] == "none"
assert create[create.index("--cpus") + 1] == cpus
assert create[create.index("--memory") + 1] == memory
assert all(command[0] != "update" for command in commands)
assert not source.exists()
def test_cleanup_remembers_only_unresolved_containers(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon"))
import infrastructure_containers as containers
marker = tmp_path / "active.json"
marker.write_text(json.dumps(dict(key="a" * 64, containers=["missing", "done", "unresolved"])))
removed = []
def inspect(name, key):
if name == "unresolved":
raise RuntimeError("Analysis container identity changed")
return {"Id": "owned-id"} if name == "done" and not removed else None
monkeypatch.setattr(containers, "inspect_owned", inspect)
monkeypatch.setattr(containers, "docker", lambda *args: removed.append(args))
with pytest.raises(RuntimeError, match="identity changed"):
containers.cleanup(marker)
assert removed == [("rm", "-f", "owned-id")]
assert json.loads(marker.read_text())["containers"] == ["unresolved"]
monkeypatch.setattr(containers, "inspect_owned", lambda *args: None)
containers.cleanup(marker)
assert json.loads(marker.read_text())["containers"] == []
def test_recalculation_is_new_idempotent_generation_and_preserves_ready(tmp_path):
store = InfrastructureJobs(tmp_path)
first = store.request(world())
key = first["key"]
store.claim(key, "owner")
store.update(key, dict(action="complete", result={"sha256": "d" * 64}), "owner")
# Cleanup still owns the GPU; force must not enqueue another run yet.
assert store.request(world(), True, "a" * 32)["key"] == key
store.update(key, dict(action="release"), "owner")
old = store.get(key)
new = store.request(world(), True, "a" * 32)
assert new["key"] != key and new["status"] == "queued"
assert store.get(key) == old
assert store.request(world(), True, "a" * 32) == new
assert store.request(world(), True, "b" * 32) == new
assert store.request(world()) == new
assert store.current(world()) == new
store.claim(new["key"], "second")
store.update(new["key"], dict(action="fail"), "second")
store.update(new["key"], dict(action="release"), "second")
assert store.get(key) == old
with pytest.raises(ValueError):
store.request(world(), True, None)
def test_eta_uses_stage_costs_never_advances_measured_progress(monkeypatch):
from k1link.simulation.ai_polygon import infrastructure_progress as progress
stages = [
dict(label="Обзор", seconds=100),
dict(label="Разметка", seconds=300),
dict(label="Проверка", seconds=100),
]
monkeypatch.setattr(progress, "plan", lambda: (stages, "measured-run"))
row = dict(status="queued", phase="queued", completed=0, total=0)
queued = progress.progress_view(row, 1000)
assert queued["eta_seconds"] == 540 and queued["fraction"] is None
row.update(status="running", started_at=1000, updated_at=1000)
progress.record_progress(row, "survey", 0, 3, 1000)
progress.record_progress(row, "refining", 1, 3, 1200)
value = progress.progress_view(row, 1205)
assert value["eta_seconds"] == 840 and value["fraction"] == 1 / 3 and value["stage"] == 2
later = progress.progress_view(row, 1210)
assert later["fraction"] == value["fraction"]
stale = progress.progress_view(row, 1230)
assert stale["stale"] and stale["eta_seconds"] is None
def test_heartbeat_does_not_restart_stage_timer_and_regression_is_rejected(tmp_path, monkeypatch):
from k1link.simulation.ai_polygon import infrastructure_jobs as module
store = InfrastructureJobs(tmp_path)
key = store.request(world())["key"]
store.claim(key, "owner")
monkeypatch.setattr(module.time, "time", lambda: 1000)
body = dict(action="progress", phase="survey", completed=1, total=91)
store.update(key, body, "owner")
monkeypatch.setattr(module.time, "time", lambda: 1005)
row = store.update(key, body, "owner")
assert (
row["stage_started_at"] == 1000
and row["updated_at"] == 1005
and len(row["stage_history"]) == 1
)
with pytest.raises(ValueError):
store.update(key, dict(body, completed=0), "owner")
@pytest.mark.parametrize("resources", [{"cpus":0}, {"cpus":13}, {"cpus":True}, {"cpus":"8"}, {"memory_gib":7}, {"memory_gib":33}, {"unknown":1}, []])
def test_invalid_container_resources_fail_before_docker_or_ownership(tmp_path, monkeypatch, resources):
monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon"))
import infrastructure_containers as containers
def forbidden(*args, **kwargs):
raise AssertionError("Invalid profile reached Docker")
monkeypatch.setattr(containers, "docker", forbidden)
marker=tmp_path/"absent.json"
with pytest.raises(ValueError, match="resource"):
containers.run_container(marker,"test","image",[],[],tmp_path,lambda:None,1,resources=resources)
assert not marker.exists()