"""Source ownership, no-collider admission and shipped pipeline closure.""" import base64 import hashlib import json from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[1] @pytest.fixture def modules(monkeypatch): monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon")) import infrastructure_gaussian_sources as sources import infrastructure_pipeline as pipeline return sources, pipeline def test_original_lcc_and_poses_are_read_only_and_mesh_is_not_opened(modules, tmp_path): sources, _ = modules job = "gsp-20261015000000-1234abcd" root = tmp_path / "jobs" / job native = root / "work/source-bundle" native.mkdir(parents=True) files = {"scan.lcc": b"{}", "data.bin": b"Gaussians"} members = [] for name, content in files.items(): (native/name).write_bytes(content) members.append(dict(logical_path=name, byte_length=len(content), sha256=hashlib.sha256(content).hexdigest())) # A producer can include a source mesh. It deliberately does not exist here; # analysis must neither require it nor treat it as evidence. members.append(dict(logical_path="Mesh_Files/scene.ply", byte_length=123, sha256="e"*64)) original = dict(format="lcc", entrypoint="scan.lcc", bundle_sha256="b"*64, members=members) (root/"job.json").write_text(json.dumps(dict(state="ready", request=dict(source=original)))) raw = json.dumps(dict(poses=[dict(T=[i*.1, 0, 1.7]) for i in range(120)])).encode() world = dict(sha256="a"*64, local_scene=dict(visual_rotation=[-180,0,0])) package = dict(world_sha256=world["sha256"], provider_job_id=job, bundle_sha256="b"*64, kind="folder", trajectory=dict(base64=base64.b64encode(raw).decode(), sha256=hashlib.sha256(raw).hexdigest(), byte_length=len(raw))) before = {p.relative_to(tmp_path).as_posix(): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} entry, poses, source = sources.resolve_native(package, world, tmp_path, tmp_path/"7z") assert entry == native/"scan.lcc" and poses == raw and source == original assert {p.relative_to(tmp_path).as_posix(): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} == before (native/"data.bin").write_bytes(b"changed!") with pytest.raises(ValueError, match="member changed"): sources.resolve_native(package, world, tmp_path, tmp_path/"7z") def test_native_frames_and_trajectory_must_be_valid(modules, tmp_path): sources, _ = modules for values in [[True,0,0], [float("nan"),0,0], [1,2], "xyz"]: raw = json.dumps(dict(poses=[dict(T=values)]*100)).encode() with pytest.raises(ValueError, match="coordinate"): sources.trajectory(raw) with pytest.raises(ValueError, match="trajectory"): sources.trajectory(b'{"poses":[]}') with pytest.raises(ValueError, match="calibration"): sources.resolve_native(dict(world_sha256="a"), dict(sha256="a", local_scene=dict(visual_rotation=[0,0,0])), tmp_path, tmp_path/"7z") for member in ["../secret", "/secret", "C:/secret", "x/../../secret", "..\\secret"]: with pytest.raises(ValueError): sources.confined(tmp_path, member) def test_analysis_does_not_require_collision_mesh(tmp_path): from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs jobs = InfrastructureJobs(tmp_path) world = dict(sha256="a"*64, world_id="aiworld-"+"a"*32, local_scene=dict(visual_rotation=[180,0,0]), collider_sha256=None) row = jobs.request(world) assert row["status"] == "queued" and row["identity"]["collider_sha256"] is None assert jobs.request(world) == row def test_bundle_uses_canonical_files_and_fails_if_staged_code_changes(modules, tmp_path): _, pipeline = modules definition, files = pipeline.definition_files() # Complexity is not an acceptance criterion: consolidating the pipeline # must not fail solely because it uses fewer groups. assert definition["schema"] == "missioncore.gaussian-infrastructure-pipeline/v1" assert definition["gaussian_only"] is True and definition["manual_rois"] == [] names = [group["group"] for group in definition["groups"]] assert names and len(names) == len(set(names)) assert all(".runtime" not in p and "qualification" not in p for p in files) assert not any("apply_review.py" == Path(p).name for p in files) definition, target, snapshot = pipeline.prepare_layout(tmp_path) assert len(snapshot) == 64 group = definition["groups"][0] alias = next(iter(group["files"])) (target/group["group"]/alias).write_text("tampered") with pytest.raises(ValueError, match="module bytes changed"): pipeline.prepare_layout(tmp_path) def test_analysis_failure_preserves_map_and_releases_only_after_cleanup(modules, monkeypatch, tmp_path): import infrastructure_preparer as preparer events = [] class Client: instance = "worker" def request(self, path, body=None, **kwargs): events.append(body.get("action") if body else "source") return {} profile = dict(job_root=str(tmp_path/"jobs"), minimum_free_gib=0, maximum_seconds=60) original_read = preparer.read_json monkeypatch.setattr(preparer, "read_json", lambda p: profile if str(p).endswith("worker-profile.json") else original_read(p)) monkeypatch.setattr(preparer, "provider_identity", lambda: "d"*64) monkeypatch.setattr(preparer, "prepare_native", lambda *a, **kw: (_ for _ in ()).throw(ValueError("bad source"))) monkeypatch.setattr(preparer, "cleanup", lambda *a: events.append("cleanup")) row = dict(key="a"*64, identity=dict(provider_sha256="d"*64), world=dict(world_id="example")) preparer.prepare_infrastructure(Client(), row, tmp_path/"state", tmp_path/"active.json") assert events == ["progress", "source", "fail", "cleanup", "release"] assert not list(tmp_path.rglob("urban-map.json")) assert not (tmp_path/"active.json").exists() def test_readonly_modules_reserve_dependency_mountpoints(modules, tmp_path): _, pipeline = modules module = tmp_path / "source" vendor = module / "pipeline/vendor" vendor.mkdir(parents=True) (vendor / "dependency.whl").write_bytes(b"pinned-wheel") (module / "stage.py").write_text("pass\n") definition = dict(groups=[dict(group="stage", stages=["stage"], files={"stage.py": "stage.py"})]) (module / "pipeline/definition.json").write_text(json.dumps(definition)) for name in ["config-ortho.json", "config-mv.json", "worker-profile.json"]: (module / "pipeline" / name).write_text("{}") _, target, _ = pipeline.prepare_layout(tmp_path / "output", module=module) slot = target / "stage/dependency.whl" assert slot.is_file() and slot.read_bytes() == b"" assert (vendor / "dependency.whl").read_bytes() == b"pinned-wheel" slot.write_bytes(b"unexpected-content") with pytest.raises(ValueError, match="Dependency mountpoint changed"): pipeline.prepare_layout(tmp_path / "output", module=module) def test_archive_trajectory_rejects_ambiguous_and_escaping_members(modules, monkeypatch, tmp_path): from types import SimpleNamespace sources, _ = modules archive = tmp_path/'original.rar' archive.write_bytes(b'archive') raw = json.dumps(dict(poses=[dict(T=[i,0,1.7])for i in range(120)])).encode() listing = f"Path = assets/poses.json\nSize = {len(raw)}\nFolder = -\n" calls = [] def run(args, **kwargs): calls.append(args) return SimpleNamespace(stdout=listing.encode() if args[1]=='l' else raw) monkeypatch.setattr(sources.subprocess, 'run', run) assert sources.read_archive_trajectory(archive, tmp_path/'7z', lambda:None) == raw assert calls[-1][-1]=='assets/poses.json' and '-spd' in calls[-1] listing += '\n'+listing with pytest.raises(ValueError, match='unambiguous'): sources.read_archive_trajectory(archive, tmp_path/'7z', lambda:None) listing = f"Path = ../poses.json\nSize = {len(raw)}\nFolder = -\n" with pytest.raises(ValueError, match='source member'): sources.read_archive_trajectory(archive, tmp_path/'7z', lambda:None) def test_host_coordinator_import_does_not_require_scientific_packages(): import subprocess,sys script = f"import sys;sys.path[:0]={[str(ROOT/'src'),str(ROOT/'simulation/ai-polygon')]!r};import infrastructure_preparer" subprocess.run([sys.executable,'-S','-c',script],check=True,capture_output=True,timeout=10) def test_archive_fallback_is_verified_cached_and_temporary_copy_removed(modules, monkeypatch, tmp_path): from types import SimpleNamespace sources, _ = modules raw = json.dumps(dict(poses=[dict(T=[i,0,1.7])for i in range(120)])).encode() archive=b'original rar';digest=hashlib.sha256(archive).hexdigest() descriptor=dict(byte_length=len(archive),sha256=digest) class Client: calls=0 def download_asset(self, path, desc, target, **options): self.calls+=1 assert path.endswith('/example/infrastructure-archive') and options['authenticated'] target.write_bytes(archive) client=Client() monkeypatch.setattr(sources.shutil,'disk_usage',lambda _:SimpleNamespace(free=100*1024**3)) monkeypatch.setattr(sources,'read_archive_trajectory',lambda *args:raw) call=lambda:sources.transferred_trajectory(descriptor,dict(world_id='example'),tmp_path,dict(sevenzip='7z'),lambda:None,client) assert call()==raw and call()==raw and client.calls==1 assert not list(tmp_path.rglob('*.archive')) and not list(tmp_path.rglob('*.part')) next(tmp_path.rglob('poses.json')).write_text('tampered') with pytest.raises(ValueError,match='trajectory changed'): call()