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.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent 25dc0a1b44
commit f48411f8fe
116 changed files with 10690 additions and 263 deletions
+491
View File
@@ -0,0 +1,491 @@
[
{
"name": "corner-incoming",
"points": [
[
0,
10,
2
],
[
0,
0,
2
],
[
10,
-1,
2
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "before"
},
{
"name": "corner-outgoing",
"points": [
[
0,
10,
2
],
[
0,
0,
2
],
[
10,
-1,
2
]
],
"index": 1,
"delta": [
3,
-0.3,
0
],
"closed": false,
"side": "after"
},
{
"name": "reversed-corner",
"points": [
[
10,
-1,
2
],
[
0,
0,
2
],
[
0,
10,
2
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "after"
},
{
"name": "straight-backward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 1,
"delta": [
-1,
0,
0
],
"closed": false,
"side": "before"
},
{
"name": "straight-forward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 1,
"delta": [
1,
0,
0
],
"closed": false,
"side": "after"
},
{
"name": "unequal-arms",
"points": [
[
-1000,
1,
2
],
[
0,
0,
2
],
[
1,
4,
2
]
],
"index": 1,
"delta": [
0.1,
1,
0
],
"closed": false,
"side": "after"
},
{
"name": "start-outward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 0,
"delta": [
-1,
0,
0
],
"closed": false,
"side": "before"
},
{
"name": "start-inward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 0,
"delta": [
1,
0,
0
],
"closed": false,
"side": "after"
},
{
"name": "end-inward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 2,
"delta": [
-1,
0,
0
],
"closed": false,
"side": "before"
},
{
"name": "end-outward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 2,
"delta": [
1,
0,
0
],
"closed": false,
"side": "after"
},
{
"name": "closed-seam-before",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
4,
4,
2
],
[
0,
4,
2
]
],
"index": 0,
"delta": [
0,
1,
0
],
"closed": true,
"side": "before"
},
{
"name": "closed-seam-after",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
4,
4,
2
],
[
0,
4,
2
]
],
"index": 0,
"delta": [
1,
0,
0
],
"closed": true,
"side": "after"
},
{
"name": "elevation-independent",
"points": [
[
0,
10,
2
],
[
0,
0,
2
],
[
10,
-1,
2
]
],
"index": 1,
"delta": [
0,
3,
1
],
"closed": false,
"side": "before"
},
{
"name": "facade-end-around-corner-positive-y",
"points": [
[
269.2913775569102,
-26.747129570459343,
3.333195732927997
],
[
295.88447329183816,
-30.768365587102007,
3.04762348870636
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "after"
},
{
"name": "facade-reversed-start-around-corner-positive-y",
"points": [
[
295.88447329183816,
-30.768365587102007,
3.04762348870636
],
[
269.2913775569102,
-26.747129570459343,
3.333195732927997
]
],
"index": 0,
"delta": [
0,
3,
0
],
"closed": false,
"side": "before"
},
{
"name": "end-near-perpendicular-negative-y",
"points": [
[
0,
-0.1,
0
],
[
10,
0,
0
]
],
"index": 1,
"delta": [
0,
-3,
0
],
"closed": false,
"side": "after"
},
{
"name": "end-dominant-inward",
"points": [
[
0,
0,
0
],
[
10,
0,
0
]
],
"index": 1,
"delta": [
-3,
1,
0
],
"closed": false,
"side": "before"
},
{
"name": "end-exact-perpendicular",
"points": [
[
0,
0,
0
],
[
10,
0,
0
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "after"
}
]
@@ -0,0 +1,185 @@
"""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()
+312
View File
@@ -0,0 +1,312 @@
"""Publication through the HTTP boundary preserves scene and worker ownership."""
import copy
import threading
from types import SimpleNamespace
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from test_infrastructure_jobs import world
from test_urban_maps import document
from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs, provider_identity
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
from k1link.web.infrastructure_api import build_infrastructure_router
@pytest.fixture
def api(tmp_path):
scene = world()
jobs, maps = InfrastructureJobs(tmp_path), UrbanMapStore(tmp_path)
released = []
def authenticate(value):
if value != "Bearer test-only":
raise HTTPException(401)
def heartbeat(value):
if value != "owner":
raise RuntimeError("Worker session expired")
def invoke(fn, *args):
try:
return fn(*args)
except FileNotFoundError as exc:
raise HTTPException(404) from exc
except ValueError as exc:
raise HTTPException(400) from exc
except RuntimeError as exc:
raise HTTPException(409) from exc
runs = SimpleNamespace(
lock=threading.RLock(),
heartbeat=heartbeat,
status=lambda: {"worker": {"infrastructure_provider_sha256": provider_identity()}},
queue=SimpleNamespace(release_simulation=released.append),
)
app = FastAPI()
app.include_router(
build_infrastructure_router(
jobs, maps, SimpleNamespace(get=lambda _: scene), runs, invoke, authenticate
)
)
return TestClient(app), jobs, maps, scene, released
def test_publish_is_idempotent_and_releases_only_after_cleanup(api):
client, jobs, maps, scene, released = api
route = f"/worlds/{scene['world_id']}/infrastructure-analysis"
row = client.post(route).json()
assert client.post(route).json() == row
key = row["key"]
jobs.claim(key, "owner")
endpoint = f"/worker/infrastructure-analysis/{key}"
headers = {"Authorization": "Bearer test-only", "Worker-Instance": "owner"}
doc = document(scene)
doc["analysis"] = dict(job_key=key, scope="whole-scene", provider_sha256=provider_identity())
assert (
client.post(
endpoint, json={"action": "complete", "map": doc}, headers={"Worker-Instance": "owner"}
).status_code
== 401
)
assert client.post(endpoint, json=[], headers=headers).status_code == 400
stale = copy.deepcopy(doc)
stale["analysis"]["provider_sha256"] = "f" * 64
assert (
client.post(
endpoint, json={"action": "complete", "map": stale}, headers=headers
).status_code
== 400
)
assert (
client.post(endpoint, json={"action": "complete", "map": doc}, headers=headers).status_code
== 200
)
assert maps.get(scene) == doc
assert (
client.post(endpoint, json={"action": "complete", "map": doc}, headers=headers).status_code
== 200
)
assert not released and jobs.pending()["status"] == "ready"
changed = copy.deepcopy(doc)
changed["features"] = []
assert (
client.post(
endpoint, json={"action": "complete", "map": changed}, headers=headers
).status_code
== 400
)
assert maps.get(scene) == doc
assert client.post(endpoint, json={"action": "release"}, headers=headers).status_code == 200
assert released == ["aicache-" + key] and jobs.pending() is None
def test_force_request_does_not_publish_or_destroy_previous_map(api):
client, jobs, maps, scene, released = api
route = f"/worlds/{scene['world_id']}/infrastructure-analysis"
old = document(scene)
maps.save(scene, old)
assert client.post(route, json={"force": True}).status_code == 400
assert client.post(route, json={"force": "yes", "request_id": "a" * 32}).status_code == 422
request = {"force": True, "request_id": "a" * 32}
first = client.post(route, json=request)
assert first.status_code == 202
assert client.post(route, json=request).json()["key"] == first.json()["key"]
assert maps.get(scene) == old
assert first.json()["progress"]["eta_seconds"] > 0
assert client.get(route).json()["progress"]["fraction"] is None
def test_cancellation_rejects_late_publication_until_owned_cleanup(api):
client, jobs, maps, scene, released = api
route = f"/worlds/{scene['world_id']}/infrastructure-analysis"
old = document(scene)
maps.save(scene, old)
row = client.post(route).json()
key = row["key"]
jobs.claim(key, "owner")
assert client.post(route + "/" + key + "/cancel").json()["cancel_requested"]
headers = {"Authorization": "Bearer test-only", "Worker-Instance": "owner"}
endpoint = f"/worker/infrastructure-analysis/{key}"
assert (
client.post(
endpoint,
json=dict(action="progress", phase="survey", completed=0, total=91),
headers=headers,
).status_code
== 409
)
doc = document(scene)
doc["analysis"] = dict(job_key=key, scope="whole-scene", provider_sha256=provider_identity())
assert (
client.post(endpoint, json=dict(action="complete", map=doc), headers=headers).status_code
== 409
)
assert maps.get(scene) == old and not released
assert (
client.post(endpoint, json=dict(action="release"), headers=headers).json()["status"]
== "cancelled"
)
assert released == ["aicache-" + key]
assert client.get("/infrastructure-analysis/queue").json() == {"jobs": []}
def test_real_worker_poll_advances_only_after_global_reservation_release(tmp_path, monkeypatch):
from test_observatory_recorded_jobs import _definitions
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
from k1link.web.ai_polygon_api import build_ai_polygon_router
monkeypatch.setattr(
"k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64
)
jobs = InfrastructureJobs(tmp_path)
first = jobs.request(world())
second_world = {**world(), "world_id": "aiworld-" + "b" * 32, "sha256": "d" * 64}
second = jobs.request(second_world)
queue = ObservatoryRecordedJobQueue(tmp_path, definitions=_definitions())
app = FastAPI()
app.include_router(build_ai_polygon_router(tmp_path, queue))
token = (tmp_path / "ai-polygon/worker.token").read_text()
headers = {"Authorization": "Bearer " + token, "Worker-Instance": "a" * 32}
root = "/api/v1/ai-polygon"
with TestClient(app) as client:
registered = client.post(
root + "/worker/register",
headers=headers,
json={
"worker_id": "worker-006",
"instance_id": "a" * 32,
"runtime": "isaac-sim-6.1",
"model_ids": ["ddrnet-goose-pytorch-reference", "rf_detr_large"],
"profile_sha256": "b" * 64,
"runtime_sources": {k: "c" * 64 for k in ("worker", "scene", "models", "robot")},
"infrastructure_provider_sha256": "f" * 64,
},
)
assert registered.status_code == 200
def poll():
r = client.post(root + "/worker/poll", headers=headers, json={"instance_id": "a" * 32})
assert r.status_code == 200
return r.json()
def update(row, action):
return client.post(
root + "/worker/infrastructure-analysis/" + row["key"],
headers=headers,
json={"action": action},
)
assert poll()["analysis"]["key"] == first["key"]
assert update(first, "fail").status_code == 200
assert poll()["action"] == "idle"
with pytest.raises(RuntimeError):
queue.reserve_simulation("airun-" + "c" * 32)
assert update(first, "release").status_code == 200
assert poll()["analysis"]["key"] == second["key"]
route = root + "/worlds/" + second_world["world_id"] + "/infrastructure-analysis/"
assert client.post(route + second["key"] + "/cancel").status_code == 200
assert poll()["action"] == "idle"
assert update(second, "release").status_code == 200
assert poll()["action"] == "idle"
queue.reserve_simulation("airun-" + "c" * 32)
queue.release_simulation("airun-" + "c" * 32)
@pytest.mark.parametrize("cancel_during_outage", [False, True])
def test_real_core_restart_preserves_running_job_and_same_worker(
tmp_path, monkeypatch, cancel_during_outage
):
from pathlib import Path
from test_observatory_recorded_jobs import _definitions
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
from k1link.simulation.ai_polygon.worlds import WorldStore
from k1link.web.ai_polygon_api import build_ai_polygon_router
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "simulation/ai-polygon"))
from core_client import CoreRequestRejected
from infrastructure_transport import report_progress
monkeypatch.setattr(
"k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64
)
scene = world()
monkeypatch.setattr(WorldStore, "get", lambda self, key: scene)
root = "/api/v1/ai-polygon"
hello = dict(
worker_id="worker-006",
instance_id="a" * 32,
runtime="isaac-sim-6.1",
model_ids=["ddrnet-goose-pytorch-reference", "rf_detr_large"],
profile_sha256="b" * 64,
runtime_sources={k: "c" * 64 for k in ("worker", "scene", "models", "robot")},
infrastructure_provider_sha256="f" * 64,
)
def core():
queue = ObservatoryRecordedJobQueue(tmp_path, definitions=_definitions())
app = FastAPI()
app.include_router(build_ai_polygon_router(tmp_path, queue))
return TestClient(app), queue
api, queue = core()
token = (tmp_path / "ai-polygon/worker.token").read_text()
headers = {"Authorization": "Bearer " + token, "Worker-Instance": hello["instance_id"]}
class Client:
instance = hello["instance_id"]
def request(self, path, body=None):
response = api.post(root + path, headers=headers, json=body)
if response.status_code != 200:
raise CoreRequestRejected(response.status_code, response.json().get("detail"))
return response.json()
client = Client()
client.request("/worker/register", hello)
jobs = InfrastructureJobs(tmp_path)
first = jobs.request(scene)
second = jobs.request({**scene, "world_id": "aiworld-" + "c" * 32, "sha256": "e" * 64})
assert (
client.request("/worker/poll", dict(instance_id=client.instance))["analysis"]["key"]
== first["key"]
)
endpoint = "/worker/infrastructure-analysis/" + first["key"]
assert report_progress(
client, endpoint, dict(phase="survey", completed=8, total=90), hello=hello
)
api.close()
# Reconstruct the actual Core router and queue from the same persisted state:
# Worker registration is lost, the job and exclusive GPU reservation survive.
api, queue = core()
jobs = InfrastructureJobs(tmp_path)
if cancel_during_outage:
jobs.cancel(first["key"])
with pytest.raises(RuntimeError):
queue.reserve_simulation("airun-" + "d" * 32)
if cancel_during_outage:
with pytest.raises(CoreRequestRejected, match="409"):
report_progress(
client, endpoint, dict(phase="refining", completed=9, total=90), hello=hello
)
assert jobs.get(first["key"])["completed"] == 8
else:
assert report_progress(
client, endpoint, dict(phase="refining", completed=9, total=90), hello=hello
)
assert jobs.get(first["key"])["completed"] == 9
doc = document(scene)
doc["analysis"] = dict(job_key=first["key"], scope="whole-scene", provider_sha256="f" * 64)
assert client.request(endpoint, dict(action="complete", map=doc))["status"] == "ready"
assert jobs.pending()["key"] == first["key"]
assert client.request(endpoint, dict(action="release"))["released"]
assert (
client.request("/worker/poll", dict(instance_id=client.instance))["analysis"]["key"]
== second["key"]
)
api.close()
+34
View File
@@ -0,0 +1,34 @@
"""Idle polls do no provider hashing; queued work still verifies current code."""
import pytest
from test_infrastructure_jobs import world
from k1link.simulation.ai_polygon import infrastructure_jobs as module
@pytest.mark.parametrize("status,released", [("running", False), ("ready", False),
("failed", True), ("ready", True)])
def test_pending_without_queue_does_not_read_source_tree(tmp_path, monkeypatch, status, released):
store = module.InfrastructureJobs(tmp_path)
monkeypatch.setattr(module, "provider_identity", lambda: "f" * 64)
row = store.request(world())
row.update(status=status, released=released)
module.write_json(store.path(row["key"]), row)
def forbidden():
raise AssertionError("idle poll hashed provider source")
monkeypatch.setattr(module, "provider_identity", forbidden)
result = store.pending()
assert result == (row if status == "running" or not released else None)
store.path(row["key"]).unlink()
assert store.pending() is None
def test_queued_work_rechecks_identity_and_rejects_source_change(tmp_path, monkeypatch):
store = module.InfrastructureJobs(tmp_path)
monkeypatch.setattr(module, "provider_identity", lambda: "f" * 64)
row = store.request(world())
assert store.pending()["key"] == row["key"]
monkeypatch.setattr(module, "provider_identity", lambda: "e" * 64)
assert store.pending() is None
assert store.get(row["key"])["status"] == "failed"
+301
View File
@@ -0,0 +1,301 @@
"""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()
+123
View File
@@ -0,0 +1,123 @@
"""Twenty-job FIFO, crash recovery and cancellation use the real durable store."""
import concurrent.futures
import pytest
from test_infrastructure_jobs import world
from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs
@pytest.fixture
def store(tmp_path, monkeypatch):
monkeypatch.setattr(
"k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64
)
return InfrastructureJobs(tmp_path)
def scene(index):
result = world()
result.update(world_id="aiworld-" + format(index, "032x"), sha256=format(index, "064x"))
return result
def test_twenty_jobs_run_fifo_after_failure_cancel_and_restart(store):
jobs = [store.request(scene(i)) for i in range(1, 21)]
assert [r["key"] for r in store.queue_rows()] == [r["key"] for r in jobs]
assert store.present(jobs[-1])["queue"]["position"] == 20
# A caller cannot jump the queue, even if it knows an identity.
with pytest.raises(RuntimeError):
store.claim(jobs[4]["key"], "worker")
first = jobs[0]["key"]
store.claim(first, "worker")
store.update(first, dict(action="fail"), "worker")
assert store.pending()["key"] == first
with pytest.raises(RuntimeError):
store.claim(jobs[1]["key"], "worker")
store.update(first, dict(action="release"), "worker")
assert store.pending()["key"] == jobs[1]["key"]
second = jobs[1]["key"]
store.claim(second, "worker")
store.cancel(second)
with pytest.raises(RuntimeError):
store.update(
second, dict(action="progress", phase="survey", completed=0, total=91), "worker"
)
with pytest.raises(RuntimeError):
store.update(second, dict(action="complete", result={}), "worker")
assert store.pending()["key"] == second
# Persisted cancellation and cleanup barrier survive a coordinator restart.
restored = InfrastructureJobs(store.root.parents[1])
assert restored.get(second)["cancel_requested"]
restored.update(second, dict(action="release", previous_owner="worker"), "new-worker")
assert restored.get(second)["status"] == "cancelled"
# Removing a waiting job never acquires a worker or delays its successor.
restored.cancel(jobs[4]["key"])
seen = []
while row := restored.pending():
seen.append(row["key"])
restored.claim(row["key"], "new-worker")
restored.update(row["key"], dict(action="complete", result={}), "new-worker")
assert restored.pending()["key"] == row["key"]
restored.update(row["key"], dict(action="release"), "new-worker")
assert seen == [j["key"] for i, j in enumerate(jobs) if i not in (0, 1, 4)]
assert restored.queue_rows() == []
def test_parallel_clicks_deduplicate_and_failed_retry_has_new_identity(store):
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
rows = list(pool.map(lambda _: store.request(scene(1), True, "a" * 32), range(20)))
assert len({r["key"] for r in rows}) == 1 and len(store.queue_rows()) == 1
key = rows[0]["key"]
store.cancel(key)
new = store.request(scene(1))
assert new["key"] != key and store.get(key)["status"] == "cancelled"
def test_pending_limit_is_explicit_and_never_discards_jobs(store):
for i in range(1, 33):
store.request(scene(i))
with pytest.raises(RuntimeError, match="Очередь заполнена"):
store.request(scene(33))
assert len(store.queue_rows()) == 32
def test_cancel_during_dispatch_cannot_strand_a_gpu_reservation(store):
import threading
from types import SimpleNamespace
row = store.request(scene(1))
entered = threading.Event()
cancel_started = threading.Event()
leases = []
def reserve(owner):
entered.set()
assert cancel_started.wait(3)
leases.append(owner)
def cancel():
assert entered.wait(3)
cancel_started.set()
return store.cancel(row["key"])
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
dispatched = pool.submit(
store.dispatch, "worker", SimpleNamespace(reserve_simulation=reserve), "f" * 64
)
cancelled = pool.submit(cancel)
assert dispatched.result(timeout=5)["status"] == "running"
assert cancelled.result(timeout=5)["status"] == "running"
assert leases == ["aicache-" + row["key"]]
assert store.get(row["key"])["cancel_requested"]
store.update(row["key"], dict(action="release"), "worker")
assert store.pending() is None
# Cancel before dispatch must not take any reservation.
waiting = store.request(scene(2))
store.cancel(waiting["key"])
assert (
store.dispatch("worker", SimpleNamespace(reserve_simulation=leases.append), "f" * 64)
is None
)
assert len(leases) == 1
+248
View File
@@ -0,0 +1,248 @@
"""Transient transport loss and a lost release receipt never strand the coordinator."""
import http.client
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture
def preparer(monkeypatch):
monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon"))
import infrastructure_preparer
monkeypatch.setattr(infrastructure_preparer.time, "sleep", lambda seconds: None)
return infrastructure_preparer
@pytest.mark.parametrize(
"error", [ConnectionAbortedError, http.client.RemoteDisconnected, TimeoutError]
)
def test_indefinite_transport_loss_is_not_calculation_failure(preparer, error):
calls = []
class Client:
def request(self, endpoint, body):
calls.append((endpoint, body))
raise error()
phase = dict(phase="survey", completed=1, total=90)
for _ in range(100):
assert preparer.report_progress(Client(), "/job", phase) is None
assert calls == [("/job", dict(action="progress", **phase))] * 100
@pytest.mark.parametrize("status", [400, 401, 403, 409])
def test_confirmed_rejection_still_stops_calculation(preparer, status):
from core_client import CoreRequestRejected
calls = []
class Client:
def request(self, *args):
calls.append(args)
raise CoreRequestRejected(status, "cancelled or invalid owner")
with pytest.raises(CoreRequestRejected):
preparer.report_progress(Client(), "/job", dict(phase="survey", completed=1, total=90))
assert len(calls) == 1
@pytest.mark.parametrize("status", [500, 502, 503, 504])
def test_temporary_gateway_outage_keeps_calculation(preparer, status):
from core_client import CoreRequestRejected
class Client:
def request(self, *args):
raise CoreRequestRejected(status, "upstream unavailable")
assert (
preparer.report_progress(Client(), "/job", dict(phase="survey", completed=1, total=90))
is None
)
def test_core_restart_recovers_registration_without_reclaim(preparer):
from core_client import CoreRequestRejected
from infrastructure_transport import EXPIRED_SESSION
calls = []
class Client:
instance = "same-owner"
def request(self, endpoint, body):
calls.append((endpoint, body))
if len(calls) == 1:
raise CoreRequestRejected(409, EXPIRED_SESSION)
return {"ok": True}
phase = dict(phase="survey", completed=8, total=90)
hello = dict(instance_id="same-owner", immutable_provider="same-provider")
assert preparer.report_progress(Client(), "/job", phase, hello=hello) == {"ok": True}
assert calls == [
("/job", dict(action="progress", **phase)),
("/worker/register", hello),
("/job", dict(action="progress", **phase)),
]
@pytest.mark.parametrize("failure", ["transport", "cleanup"])
def test_failed_receipt_keeps_marker_until_reconnect_and_cleanup(
preparer, monkeypatch, tmp_path, failure
):
events = []
class Client:
instance = "worker"
online = False
def request(self, path, body=None, **kwargs):
action = body.get("action") if body else "source"
events.append(action)
if action in ("fail", "release") and not self.online:
raise ConnectionAbortedError()
return {}
client = Client()
profile = dict(job_root=str(tmp_path / "jobs"), minimum_free_gib=0, maximum_seconds=60)
read = preparer.read_json
monkeypatch.setattr(
preparer,
"read_json",
lambda p: profile if str(p).endswith("worker-profile.json") else read(p),
)
monkeypatch.setattr(preparer, "provider_identity", lambda: "d" * 64)
def source(*args, **kwargs):
raise ValueError("Invalid source")
def cleanup(marker):
events.append("cleanup")
if failure == "cleanup" and not client.online:
raise RuntimeError("Docker unavailable; cannot prove release")
monkeypatch.setattr(preparer, "prepare_native", source)
monkeypatch.setattr(preparer, "cleanup", cleanup)
row = dict(
key="a" * 64, identity=dict(provider_sha256="d" * 64), world=dict(world_id="example")
)
marker = tmp_path / "active.json"
# The coordinator must regain control even when fail AND release fail.
preparer.prepare_infrastructure(client, row, tmp_path / "state", marker)
assert marker.exists()
assert not list(tmp_path.rglob("urban-map.json"))
if failure == "cleanup":
assert "release" not in events
client.online = True
preparer.reconcile(client, marker)
assert events[-2:] == ["cleanup", "release"]
assert not marker.exists()
# Idempotent retry after acknowledgement cannot release a different job.
count = len(events)
preparer.reconcile(client, marker)
assert len(events) == count
def outbox(preparer, monkeypatch, tmp_path):
profile = dict(job_root=str(tmp_path), maximum_seconds=60)
read = preparer.read_json
monkeypatch.setattr(
preparer,
"read_json",
lambda p: profile if str(p).endswith("worker-profile.json") else read(p),
)
key = "a" * 64
output = tmp_path / key
output.mkdir()
preparer.write_json(output / "urban-map.json", {"features": [], "verified": "fixture"})
marker = tmp_path / "active.json"
preparer.write_json(
marker,
dict(
key=key,
owner="worker",
containers=[],
completion=dict(sha256=preparer.checksum(output / "urban-map.json")),
),
)
return marker, output
@pytest.mark.parametrize("lost_ack", [False, True])
def test_result_outbox_survives_outage_and_lost_ack(preparer, monkeypatch, tmp_path, lost_ack):
marker, output = outbox(preparer, monkeypatch, tmp_path)
events, maps = [], []
class Client:
instance = "worker"
online = False
def request(self, path, body):
events.append(body["action"])
if body["action"] == "complete":
if self.online or lost_ack:
if maps:
assert maps[0] == body["map"]
else:
maps.append(body["map"])
if not self.online:
raise ConnectionResetError()
return {"ok": True}
client = Client()
for _ in range(4):
with pytest.raises(ConnectionResetError):
preparer.reconcile(client, marker)
assert marker.exists() and preparer.read_json(marker)["completion"]
assert "release" not in events
client.online = True
preparer.reconcile(client, marker)
assert events[-2:] == ["complete", "release"] and len(maps) == 1
assert not marker.exists() and (output / "urban-map.json").exists()
def test_cancel_while_result_offline_rejects_publication_then_releases(
preparer, monkeypatch, tmp_path
):
from core_client import CoreRequestRejected
marker, output = outbox(preparer, monkeypatch, tmp_path)
events = []
class Client:
def request(self, path, body):
events.append(body["action"])
if body["action"] == "complete":
raise CoreRequestRejected(409, "Analysis cancellation requested")
return {}
preparer.reconcile(Client(), marker)
assert events == ["complete", "release"] and not marker.exists()
assert (output / "publication-rejection.json").exists()
def test_pending_result_tamper_keeps_queue_barrier(preparer, monkeypatch, tmp_path):
marker, output = outbox(preparer, monkeypatch, tmp_path)
(output / "urban-map.json").write_text("{}")
with pytest.raises(ValueError, match="result changed"):
preparer.reconcile(object(), marker)
assert marker.exists()
def test_source_read_retries_transport_only(preparer):
calls = []
class Client:
def request(self, path, **kwargs):
calls.append(path)
if len(calls) < 5:
raise ConnectionResetError()
return {"source": "verified"}
assert preparer.source_package(Client(), "/source", lambda: None, float("inf")) == {
"source": "verified"
}
assert len(calls) == 5
+36
View File
@@ -0,0 +1,36 @@
import json
from pathlib import Path
import sys
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'simulation/ai-polygon'))
from infrastructure_survey_cache import file_hash, find_survey, record_survey
def make_survey(tmp_path):
folder=tmp_path/'old';part=folder/'tile-000-000';part.mkdir(parents=True)
request={'source':{'sha256':'source'},'model':{'revision':'model'}}
(part/'job.json').write_text(json.dumps(request))
files={}
for name in ('top.png','top.geometry.npz','surface-atlas.npz'):
(part/name).write_bytes(b'original-derived-data');files[name]=file_hash(part/name)
(part/'survey-receipt.json').write_text(json.dumps({'status':'surveyed','job_sha256':file_hash(part/'job.json'),'files':files}))
(folder/'tile-index.json').write_text(json.dumps({'tiles':[{'id':part.name,'status':'surveyed'}]}))
return folder,request
def test_reuse_returns_existing_directory_without_copy_and_rejects_changed_data(tmp_path):
folder,request=make_survey(tmp_path)
record_survey(folder,request,'survey-v1',lambda:None)
before={str(p.relative_to(tmp_path)) for p in tmp_path.rglob('*')}
assert find_survey(tmp_path,request,'survey-v1',lambda:None)==folder
assert before=={str(p.relative_to(tmp_path)) for p in tmp_path.rglob('*')}
assert find_survey(tmp_path,request,'survey-v2',lambda:None) is None
assert find_survey(tmp_path,{**request,'source':{}},'survey-v1',lambda:None) is None
(folder/'tile-000-000/top.png').write_bytes(b'corrupt')
assert find_survey(tmp_path,request,'survey-v1',lambda:None) is None
def test_partial_survey_is_never_admitted_as_complete(tmp_path):
folder,request=make_survey(tmp_path)
(folder/'tile-index.json').write_text(json.dumps({'tiles':[{'id':'tile-000-000','status':'pending'}]}))
with pytest.raises(ValueError,match='incomplete'):
record_survey(folder,request,'survey-v1',lambda:None)
assert not (folder/'survey-cache.json').exists()
+87
View File
@@ -0,0 +1,87 @@
"""A missing optional collider must not hide a valid Gaussian project."""
import hashlib
from types import SimpleNamespace
import pytest
from k1link.simulation.ai_polygon.editor_cache import EditorCache
from k1link.simulation.ai_polygon.project_worlds import ProjectWorlds
from k1link.simulation.ai_polygon.contracts import RunCreate
from test_ai_polygon import runs
def project_worlds(tmp_path, collision):
pid = "sim-" + "a" * 32
prefix = f"/api/v1/simulation-worlds/projects/{pid}/artifacts/"
artifacts = []
for name in ["streamed/lod-meta.json"] + (["collision.glb"] if collision else []):
path = tmp_path / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"fixture")
artifacts.append(dict(logical_path=name, byte_length=7,
sha256=hashlib.sha256(b"fixture").hexdigest()))
project = dict(project_id=pid, name="Gaussian scan", created_at_utc="2026-10-15T00:00:00Z",
source={"bundle_sha256": "b" * 64}, provider={"job_id": "gsp-test"},
artifacts=artifacts,
viewer_settings={k: {"rotation_degrees": dict(x=0, y=0, z=0)}
for k in ("visual", "collision")},
world_manifest={"visual": dict(streamed_sog_url=prefix + artifacts[0]["logical_path"],
preview_sog_url=None),
"collision": {"mesh_url": prefix + "collision.glb" if collision else None}})
worlds = object.__new__(ProjectWorlds)
worlds.projects = SimpleNamespace(get=lambda _: project, list=lambda: [project],
artifact_path=lambda _, name: (tmp_path / name, next(a for a in artifacts if a["logical_path"] == name)))
return worlds, project
@pytest.mark.parametrize("collision", [False, True])
def test_catalog_package_and_editor_preserve_available_assets(tmp_path, collision):
projects, project = project_worlds(tmp_path, collision)
world, = projects.list()
assert world["settings"]["prepared"]
assert world["inference_ready"] is collision
assert bool(world["collider_sha256"]) is collision
assert bool(world["inference_message"]) is not collision
package = projects.package(world)
assert package["visual_path"] == "streamed/lod-meta.json"
assert package["collision_path"] == ("collision.glb" if collision else None)
cache = EditorCache(tmp_path / "cache", SimpleNamespace(projects=projects, get=lambda _: world))
row = cache.request(world["world_id"])
assert row["status"] == "ready"
assert set(row["files"]) == ({"scene.sog", "collision.glb"} if collision else {"scene.sog"})
assert cache.get(row["key"])["local_scene"] == world["local_scene"]
def test_present_but_invalid_collider_is_not_silently_ignored(tmp_path):
worlds, project = project_worlds(tmp_path, True)
project["world_manifest"]["collision"]["mesh_url"] = "https://example.invalid/collision.glb"
with pytest.raises(ValueError, match="отсутствует"):
worlds.list()
def test_missing_visual_is_still_rejected(tmp_path):
worlds, project = project_worlds(tmp_path, False)
project["world_manifest"]["visual"]["streamed_sog_url"] = None
with pytest.raises(ValueError, match="отсутствует"):
worlds.list()
def test_visual_only_world_cannot_start_rover(runs, monkeypatch):
store, _, world = runs
world.update(inference_ready=False, inference_message="Нужна поверхность коллизий.")
monkeypatch.setattr(store.worlds, "get", lambda _: world)
with pytest.raises(RuntimeError, match="Нужна поверхность"):
store.start(RunCreate(world_id=world["world_id"]), "visual-only-world-test")
def test_analysis_archive_is_bound_to_world_and_confined(tmp_path):
worlds, project = project_worlds(tmp_path, False)
raw=b'original archive';(tmp_path/'scan.rar').write_bytes(raw)
project['source'].update(kind='archive',files=[dict(logical_path='scan.rar',byte_length=len(raw),sha256=hashlib.sha256(raw).hexdigest())])
worlds.projects.source_root=lambda _:tmp_path
world=worlds.world(project)
path,descriptor=worlds.analysis_archive(world)
assert path.read_bytes()==raw and descriptor['sha256']==hashlib.sha256(raw).hexdigest()
project['source']['files'][0]['logical_path']='../scan.rar'
with pytest.raises(ValueError,match='escaped'):
worlds.analysis_archive(world)
+85
View File
@@ -0,0 +1,85 @@
import copy
import hashlib
import json
import pytest
from k1link.simulation.ai_polygon.qualified_maps import qualified_document
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore, validate_map
def source():
return dict(schema_version="missioncore.refined-full-plan-research/v1", type="FeatureCollection",
point_clouds=False, manual_geometry=False, features=[dict(type="Feature", id="front-1",
properties=dict(**{"class": "building_facade"}, review_status="unreviewed"),
geometry=dict(type="LineString", coordinates=[[1, 2, 3], [4, 5, 6]]))])
WORLD = {"sha256": "a" * 64, "collider_sha256": "b" * 64}
def adapt(plan=None, **kwargs):
raw = json.dumps(source() if plan is None else plan).encode()
options = dict(artifact_sha256=hashlib.sha256(raw).hexdigest(), source_world_sha256=WORLD["sha256"],
qualification="symbol-pass-20261014", source_snapshot="test", tiles_total=3)
return qualified_document(raw, WORLD, **{**options, **kwargs})
def test_lossless_geometry_and_honest_confidence(tmp_path):
plan = source()
result = adapt(plan)
assert result["features"][0]["geometry"] == plan["features"][0]["geometry"]
p = result["features"][0]["properties"]
assert p["confidence"] is None and p["confidence_status"] == "not-assessed"
assert p["authority"] == "observation-only" and p["route_permission"] == "unassigned"
assert "confidence" not in plan["features"][0]["properties"]
store = UrbanMapStore(tmp_path)
store.save(WORLD, result)
assert store.get(WORLD) == result
@pytest.mark.parametrize("change", [dict(artifact_sha256="0" * 64), dict(source_world_sha256="c" * 64), dict(tiles_total=-1)])
def test_changed_or_foreign_source_rejected(change):
with pytest.raises(ValueError): adapt(**change)
@pytest.mark.parametrize("property,value", [("route_permission", "allowed"), ("authority", "navigation")])
def test_import_never_promotes_authority(property, value):
plan = source(); plan["features"][0]["properties"][property] = value
with pytest.raises(ValueError): adapt(plan)
def test_null_confidence_requires_v3_explicit_unknown():
result = adapt()
bad = copy.deepcopy(result); bad["schema_version"] = "missioncore.urban-map/v2"
with pytest.raises(ValueError): validate_map(bad, WORLD)
bad = copy.deepcopy(result); del bad["features"][0]["properties"]["confidence_status"]
with pytest.raises(ValueError): validate_map(bad, WORLD)
bad = copy.deepcopy(result); bad["features"][0]["properties"]["confidence"] = float("nan")
with pytest.raises(ValueError): validate_map(bad, WORLD)
def test_polygons_holes_and_open_ends_stay_exact():
plan = source(); plan["features"].append(dict(type="Feature", id="bike-1",
properties={"class":"road_marking","subtype":"bicycle"}, geometry=dict(type="Polygon",coordinates=[
[[0,0,0],[4,0,0],[4,4,0],[0,4,0],[0,0,0]],[[1,1,0],[1,2,0],[2,2,0],[2,1,0],[1,1,0]]])))
result = adapt(plan)
assert [f["geometry"] for f in result["features"]] == [f["geometry"] for f in plan["features"]]
def test_systematic_plan_is_lossless_and_keeps_observation_authority():
plan = source()
plan["schema_version"] = "missioncore.systematic-plan/v1"
result = adapt(plan)
assert result["features"][0]["geometry"] == plan["features"][0]["geometry"]
assert result["features"][0]["properties"]["route_permission"] == "unassigned"
plan["features"][0]["properties"]["authority"] = "navigation"
with pytest.raises(ValueError):
adapt(plan)
def test_unregistered_plan_schema_still_fails():
plan = source()
plan["schema_version"] = "missioncore.systematic-plan/v999"
with pytest.raises(ValueError, match="qualified automatic Gaussian plan"):
adapt(plan)
+120
View File
@@ -0,0 +1,120 @@
"""Idle Worker polling must not repeatedly parse completed scene geometry."""
import json
import os
from pathlib import Path
import pytest
from k1link.simulation.ai_polygon.route_preparation import RoutePreparationStore
from k1link.simulation.ai_polygon.run_inputs import digest
def put(store, identity=None, status="failed", owner=None):
identity = identity or {"case": 1}
key = digest(identity)
row = dict(key=key, identity=identity, status=status, owner=owner, result=None)
path = store.path(key)
path.write_text(json.dumps(row))
return path, row
def test_idle_scan_skips_unchanged_completed_payload(tmp_path, monkeypatch):
store = RoutePreparationStore(tmp_path)
path, _ = put(store)
assert store.pending() is None
original = Path.read_text
def forbid_read(candidate, *args, **kwargs):
assert candidate != path, "unchanged completed geometry was parsed again"
return original(candidate, *args, **kwargs)
monkeypatch.setattr(Path, "read_text", forbid_read)
assert store.pending() is None
assert store.pending() is None
def test_external_same_size_change_preserved_mtime_is_not_hidden(tmp_path):
store = RoutePreparationStore(tmp_path)
path, row = put(store)
assert store.pending() is None
before = path.stat()
row["status"] = "queued" # exactly the same encoded length
path.write_text(json.dumps(row))
os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns))
assert path.stat().st_size == before.st_size
assert store.pending() == row
assert store.claim(row["key"], "worker")["status"] == "preparing"
with pytest.raises(RuntimeError, match="another Worker"):
store.claim(row["key"], "other")
def test_atomic_replacement_and_new_jobs_are_visible(tmp_path):
store = RoutePreparationStore(tmp_path)
path, row = put(store)
assert store.pending() is None
row["status"] = "queued"
replacement = path.with_suffix(".tmp")
replacement.write_text(json.dumps(row))
replacement.replace(path)
assert store.pending() == row
path.unlink()
assert store.pending() is None
assert not store._inactive_files
_, other = put(store, {"case": 2}, "queued")
assert store.pending() == other
def test_pending_and_claim_still_validate_identity(tmp_path):
store = RoutePreparationStore(tmp_path)
path, row = put(store)
assert store.pending() is None
row.update(status="queued", identity={"forged": True})
path.write_text(json.dumps(row))
with pytest.raises(ValueError, match="identity changed"):
store.pending()
with pytest.raises(ValueError, match="identity changed"):
store.claim(row["key"], "worker")
def test_broken_changed_file_and_symlink_fail_closed(tmp_path):
store = RoutePreparationStore(tmp_path)
path, _ = put(store)
assert store.pending() is None
path.write_text("{")
with pytest.raises(json.JSONDecodeError):
store.pending()
path.unlink()
target = tmp_path / "target.json"
target.write_text("{}")
path.symlink_to(target)
with pytest.raises(ValueError, match="Invalid route"):
store.pending()
def test_metadata_index_bounded_and_contains_no_geometry(tmp_path):
store = RoutePreparationStore(tmp_path)
for number in range(514):
put(store, {"case": number})
assert store.pending() is None
assert len(store._inactive_files) == 512
assert all(len(stamp) == 5 and all(isinstance(n, int) for n in stamp)
for stamp in store._inactive_files.values())
def test_file_changed_during_parse_is_not_cached(tmp_path, monkeypatch):
store = RoutePreparationStore(tmp_path)
path, row = put(store)
original = Path.read_text
def mutate(candidate, *args, **kwargs):
content = original(candidate, *args, **kwargs)
if candidate == path:
row["status"] = "queued"
path.write_text(json.dumps(row))
return content
monkeypatch.setattr(Path, "read_text", mutate)
assert store.pending() is None
assert not store._inactive_files
monkeypatch.setattr(Path, "read_text", original)
assert store.pending() == row
+240
View File
@@ -0,0 +1,240 @@
"""Human revisions never mutate inference; test failures before/after durable commit."""
import copy
import json
from concurrent.futures import ThreadPoolExecutor
import pytest
from test_urban_maps import document
from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, apply_operations
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
def make_setup(tmp_path):
world = {"sha256": "a" * 64, "collider_sha256": "b" * 64}
model = document(world)
model["schema_version"] = "missioncore.urban-map/v3"
model["source"].update(gaussian_only=True, artifact_sha256="c" * 64)
model["features"] = [
{
"type": "Feature",
"id": "curb-1",
"properties": {
"class": "curb",
"authority": "observation-only",
"route_permission": "unassigned",
"confidence": 0.9,
"review_status": "accepted",
},
"geometry": {"type": "LineString", "coordinates": [[0, 0, 2], [2, 0, 2], [4, 1, 2]]},
},
{
"type": "Feature",
"id": "facade-1",
"properties": {
"class": "building_facade",
"authority": "observation-only",
"route_permission": "unassigned",
"confidence": 0.8,
"review_status": "accepted",
},
"geometry": {"type": "LineString", "coordinates": [[0, 5, 2], [4, 5, 2]]},
},
]
maps = UrbanMapStore(tmp_path)
receipt = maps.save(world, model)
store = SemanticEdits(tmp_path, maps)
return world, model, maps, store, receipt["sha256"]
@pytest.fixture
def setup(tmp_path):
return make_setup(tmp_path)
def change(sha, *, request="first-request-0001", parent=None):
return {
"expected_revision": parent,
"model_sha256": sha,
"request_id": request,
"operations": [
{"kind": "move", "feature_id": "curb-1", "path": 0, "index": 1, "position": [2, 0.5, 2]}
],
}
def test_save_restart_repeat_and_source_immutability(setup):
world, model, maps, store, sha = setup
saved = store.save(world, change(sha))
assert maps.get(world) == model
assert saved["model"] == model
assert saved["edited"]["features"][1] == model["features"][1]
assert saved["edited"]["schema_version"] == "missioncore.urban-edit/v1"
assert "gaussian_only" not in saved["edited"]["source"]
assert not saved["learning"]["dataset_ready"]
restarted = SemanticEdits(store.root.parents[1], maps)
assert restarted.get(world) == saved
assert restarted.save(world, change(sha)) == saved
assert len(json.loads(store._path(world).read_text())["revisions"]) == 1
altered = change(sha)
altered["operations"][0]["position"][0] = 3
with pytest.raises(RuntimeError, match="идентификатор|Идентификатор"):
store.save(world, altered)
def test_frozen_model_survives_new_analysis_and_conflict(setup):
world, model, maps, store, sha = setup
first = store.save(world, change(sha))
newer = copy.deepcopy(model)
newer["features"][0]["geometry"]["coordinates"][1] = [2, -0.5, 2]
maps.save(world, newer)
view = store.get(world)
assert view["model"] == model
assert view["latest_model_sha256"] != sha
with pytest.raises(RuntimeError, match="другом окне"):
store.save(world, change(sha, request="second-request-0002"))
second = change(sha, request="second-request-0002", parent=first["revision"])
second["operations"] = [
{"kind": "insert", "feature_id": "curb-1", "path": 0, "index": 0, "t": 0.5}
]
assert len(store.save(world, second)["history"]) == 2
assert maps.get(world) == newer
def test_concurrent_save_has_one_winner(setup):
world, _, _, store, sha = setup
def save(i):
try:
return store.save(world, change(sha, request=f"concurrent-request-{i:04}"))
except RuntimeError:
return None
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(save, (1, 2)))
assert sum(r is not None for r in results) == 1
assert len(store.get(world)["history"]) == 1
def test_no_approximation_insert_and_delete_roundtrip(setup):
_, model, _, _, _ = setup
inserted = apply_operations(
model, [{"kind": "insert", "feature_id": "curb-1", "path": 0, "index": 0, "t": 0.25}]
)
assert inserted["features"][0]["geometry"]["coordinates"] == [
[0, 0, 2],
[0.5, 0, 2],
[2, 0, 2],
[4, 1, 2],
]
restored = apply_operations(
inserted, [{"kind": "delete", "feature_id": "curb-1", "path": 0, "index": 1}]
)
assert restored["features"][0]["geometry"] == model["features"][0]["geometry"]
def test_no_op_preserves_evidence_and_does_not_create_revision(setup):
world, model, _, store, sha = setup
body = change(sha)
body["operations"][0]["position"] = [2, 0, 2]
assert apply_operations(model, body["operations"]) == model
with pytest.raises(ValueError, match="Нет изменений"):
store.save(world, body)
assert store.get(world)["revision"] is None
@pytest.mark.parametrize("position", [[2, 0, 3], [0, 0, 2], [float("nan"), 0, 2], [True, 0, 2]])
def test_invalid_save_never_commits(setup, position):
world, _, _, store, sha = setup
body = change(sha)
body["operations"][0]["position"] = position
with pytest.raises(ValueError):
store.save(world, body)
assert store.get(world)["revision"] is None
def test_polygon_closure_and_crossing_rejection(setup):
_, model, _, _, _ = setup
model["features"][0]["geometry"] = {
"type": "Polygon",
"coordinates": [[[0, 0, 2], [2, 0, 2], [2, 2, 2], [0, 2, 2], [0, 0, 2]]],
}
moved = apply_operations(
model,
[{"kind": "move", "feature_id": "curb-1", "path": 0, "index": 0, "position": [-0.5, 0, 2]}],
)
ring = moved["features"][0]["geometry"]["coordinates"][0]
assert ring[0] == ring[-1] == [-0.5, 0, 2]
with pytest.raises(ValueError, match="самопересечение"):
apply_operations(
model,
[
{
"kind": "move",
"feature_id": "curb-1",
"path": 0,
"index": 1,
"position": [1, 3, 2],
}
],
)
def test_corrupt_history_refused_and_budget_preserves_state(setup, monkeypatch):
world, _, _, store, sha = setup
monkeypatch.setattr("k1link.simulation.ai_polygon.semantic_edits.MAX_STATE", 1)
with pytest.raises(ValueError, match="Лимит"):
store.save(world, change(sha))
assert not store._path(world).exists()
monkeypatch.undo()
store.save(world, change(sha))
state = json.loads(store._path(world).read_text())
state["revisions"][0]["operations"][0]["position"][0] = 9
store._path(world).write_text(json.dumps(state))
with pytest.raises(ValueError, match="целостность"):
store.get(world)
def test_directional_duplicate_persists_without_reinterpreting_prior_history(setup):
world, model, maps, store, sha = setup
first = store.save(world, change(sha))
request = change(sha, request="directional-copy-0002", parent=first["revision"])
request["operations"] = [{
"kind": "duplicate_vertex", "feature_id": "curb-1", "path": 0,
"index": 1, "delta": [-0.5, 0, 0], "axis": "x", "side": "before",
}]
saved = store.save(world, request)
assert saved["edited"]["features"][0]["geometry"]["coordinates"] == [
[0, 0, 2], [1.5, 0.5, 2], [2, 0.5, 2], [4, 1, 2],
]
assert SemanticEdits(store.root.parents[1], maps).get(world) == saved
assert store.export(world, first["revision"])["package"]["edited"] == first["edited"]
assert maps.get(world) == model
def test_save_returns_admitted_geometry_without_a_second_history_replay(setup, monkeypatch):
from k1link.simulation.ai_polygon import semantic_edits
world, _, maps, store, sha = setup
first = store.save(world, change(sha))
request = change(sha, request="admitted-save-0002", parent=first["revision"])
request["origin"] = "agent-proposal"
request["operations"] = [dict(kind="duplicate_vertex", feature_id="curb-1", path=0,
index=2, delta=[1, 0, 0], axis="x", side="after")]
real = semantic_edits.apply_operations
admitted = []
replayed = []
def track(*args, **kwargs):
result = real(*args, **kwargs)
(replayed if kwargs.get("verified_history") else admitted).append(result)
return result
monkeypatch.setattr(semantic_edits, "apply_operations", track)
saved = store.save(world, request)
assert len(replayed) == len(first["history"])
assert len(admitted) == 1 and saved["edited"] is admitted[0]
assert saved["edited"]["features"][0]["properties"]["annotation_origin"] == "agent-proposal"
assert SemanticEdits(store.root.parents[1], maps).get(world) == saved
assert store.save(world, request) == saved
+162
View File
@@ -0,0 +1,162 @@
"""Exercise real HTTP admission without starting or mutating the operator service."""
import copy
import json
from types import SimpleNamespace
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from test_semantic_edits import change, make_setup
from k1link.simulation.ai_polygon.semantic_edits import MAX_STATE, SemanticEdits
from k1link.web.semantic_edits_api import build_semantic_edits_router
def test_http_limits_conflict_and_worker_export(tmp_path):
world, model, maps, store, sha = make_setup(tmp_path)
world["world_id"] = "fixture"
def invoke(fn, *args):
try:
return fn(*args)
except FileNotFoundError as exc:
raise HTTPException(404) from exc
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(409, str(exc)) from exc
def authenticate(authorization):
if authorization != "Bearer synthetic-test-token":
raise HTTPException(401)
app = FastAPI()
app.include_router(
build_semantic_edits_router(
store.root.parents[1],
SimpleNamespace(get=lambda _: world, list=lambda: [world]),
maps,
invoke,
authenticate,
)
)
with TestClient(app) as client:
path = "/worlds/fixture/semantic-edits"
assert client.get("/worker/semantic-edits/pending").status_code == 401
assert client.get(path).json()["model"] == model
assert client.post(path, content=b"x" * (MAX_STATE + 1)).status_code == 413
assert client.post(path, json={"image": "not-allowed"}).status_code == 400
saved = client.post(path, json=change(sha))
assert saved.status_code == 200
revision = saved.json()["revision"]
assert client.post(path, json=change(sha)).json()["revision"] == revision
assert client.post(path, json=change(sha, request="conflicting-save-02")).status_code == 409
export_path = f"/worker/worlds/fixture/semantic-edits/{revision}"
assert client.get(export_path).status_code == 401
exported = client.get(export_path, headers={"Authorization": "Bearer synthetic-test-token"})
assert exported.status_code == 200
assert exported.json() == store.export(world, revision)
assert not exported.json()["package"]["review"]["dataset_ready"]
assert client.get(path).json()["model"] == model
headers = {"Authorization": "Bearer synthetic-test-token"}
assert (
client.get("/worker/semantic-edits/pending", headers=headers).json()["jobs"][0][
"revision"
]
== revision
)
receipt = {
"state": "received",
"package_sha256": exported.json()["sha256"],
"dataset_sha256": None,
"sample_count": 0,
}
ack = export_path + "/receipt"
assert client.post(ack, json=receipt).status_code == 401
assert client.post(ack, json=receipt, headers=headers).status_code == 200
assert client.post(ack, json=receipt, headers=headers).status_code == 200
assert client.get("/worker/semantic-edits/pending", headers=headers).json()["jobs"] == []
assert client.get(path + "/status").json()["state"] == "received"
assert client.post(ack, content=b"x" * 2049, headers=headers).status_code == 413
def test_large_group_edit_round_trip_and_atomic_rejection(tmp_path):
world, model, maps, store, _ = make_setup(tmp_path)
feature = model["features"][0]
feature["id"] = fid = "road-" + "a" * 64
feature["geometry"]["coordinates"] = [[i, 0, 2] for i in range(20)]
sha = maps.save(world, model)["sha256"]
op = {
"kind": "translate_vertices", "feature_id": fid,
"vertices": [{"feature_id": fid, "path": 0, "index": i} for i in range(20)],
"axis": "y", "delta": [0, 0.125, 0],
}
body = change(sha, request="large-group-edit-0001")
body["operations"] = [copy.deepcopy(op) for _ in range(162)]
raw = json.dumps(body).encode()
assert 256 * 1024 < len(raw) < MAX_STATE
def invoke(fn, *args):
try:
return fn(*args)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(409, str(exc)) from exc
app = FastAPI()
app.include_router(build_semantic_edits_router(
tmp_path, SimpleNamespace(get=lambda _: world), maps, invoke, lambda _: None,
))
path = "/worlds/fixture/semantic-edits"
with TestClient(app) as client:
saved = client.post(path, content=raw, headers={"Content-Type": "application/json"})
assert saved.status_code == 200, saved.text
view = saved.json()
assert view["edited"]["features"][0]["geometry"]["coordinates"] == [
[i, 20.25, 2] for i in range(20)
]
assert view["history"][-1]["actions"] == 162
assert view["model"] == model
assert client.post(path, json=body).json()["revision"] == view["revision"]
assert SemanticEdits(tmp_path, maps).get(world) == view
before = store._path(world).read_bytes()
invalid = {
**body, "request_id": "invalid-large-edit-02", "expected_revision": view["revision"]
}
invalid["operations"] = body["operations"] + [{
"kind": "move", "feature_id": fid, "path": 0, "index": 1,
"position": [2, 40.5, 2],
}]
# The final move coincides with the next vertex after the valid prefix.
assert client.post(path, json=invalid).status_code == 400
conflict = {**body, "request_id": "conflicting-large-03"}
assert client.post(path, json=conflict).status_code == 409
assert store._path(world).read_bytes() == before
assert client.get(path).json() == view
def test_save_and_worker_receipt_run_outside_the_event_loop(tmp_path, monkeypatch):
import threading
world, _, maps, store, _ = make_setup(tmp_path)
monkeypatch.setattr(SemanticEdits, "save", lambda *args: {"thread": threading.get_ident()})
monkeypatch.setattr(SemanticEdits, "receipt", lambda *args: {"thread": threading.get_ident()})
app = FastAPI()
@app.get("/probe")
async def probe():
return {"thread": threading.get_ident()}
app.include_router(build_semantic_edits_router(
store.root.parents[1], SimpleNamespace(get=lambda _: world), maps,
lambda fn, *args: fn(*args), lambda _: None,
))
with TestClient(app) as client:
event_loop = client.get("/probe").json()["thread"]
for path in ("/worlds/fixture/semantic-edits",
"/worker/worlds/fixture/semantic-edits/revision/receipt"):
response = client.post(path, json={})
assert response.status_code == 200
assert response.json()["thread"] != event_loop
+127
View File
@@ -0,0 +1,127 @@
import json
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "simulation/ai-polygon"))
import infrastructure_pipeline as pipeline # noqa: E402 - canonical worker modules
def definition():
return {
"groups": [
{
"group": "base",
"stages": ["ortho_semantic_survey"],
"files": {"ortho_semantic_survey.py": "stage.py"},
"stage_outputs": {"ortho_semantic_survey": {"/layers": "full_plan"}},
},
{
"group": "full_plan",
"stages": ["assemble_layers"],
"files": {"assemble_layers.py": "assemble.py"},
},
],
"aliases": {"full_plan": "fullplan"},
}
def test_full_runner_passes_joint_outputs_to_original_consumer(tmp_path, monkeypatch):
module = tmp_path / "module"
(module / "pipeline").mkdir(parents=True)
(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(json.dumps({"models": {}}))
(module / "stage.py").write_text("pass\n")
(module / "assemble.py").write_text("pass\n")
package = tmp_path / "input"
package.mkdir()
(package / "poses.json").write_text("{}")
output = tmp_path / "output"
output.mkdir()
calls = []
def run(marker, phase, image, mounts, cmd, out, pulse, timeout, **kwargs):
calls.append((phase, image, mounts, kwargs))
m = {alias: (path, ro) for path, alias, ro in mounts}
if "semantic" in phase:
assert image == "semantic-image" and kwargs["gpu"]
assert m["/run"] == (output / "ortho", False)
assert m["/layers"] == (output / "full_plan", False)
assert m["/input"] == (package, True)
(m["/layers"][0] / "evidence").mkdir()
(m["/layers"][0] / "evidence/report.json").write_text('{"complete":true}')
else:
assert image == "mapper-image" and not kwargs["gpu"]
assert json.loads((out / "evidence/report.json").read_text())["complete"]
(out / "full-map.json").write_text('{"features":[]}')
monkeypatch.setattr(pipeline, "run_container", run)
result, snapshot = pipeline.run_pipeline(
package,
{"sha256": "a" * 64, "poses_sha256": "b" * 64},
output,
tmp_path / "marker",
{
"maximum_seconds": 1000,
"maximum_stage_seconds": 100,
"semantic_model": "assets/model",
"semantic_image": "semantic-image",
"mapper_image": "mapper-image",
},
tmp_path / "runtime",
lambda: None,
module=module,
)
assert result == output / "full_plan/full-map.json" and len(snapshot) == 64
assert len(calls) == 2 and (output / "full_plan/group-inventory.json").is_file()
@pytest.mark.parametrize("target", ["base", "missing", "../private", "/input"])
def test_invalid_target_refused(target):
d = definition()
d["groups"][0]["stage_outputs"]["ortho_semantic_survey"]["/layers"] = target
with pytest.raises(ValueError):
pipeline.validate_stage_outputs(d)
@pytest.mark.parametrize("alias", ["/input", "/fullplan", "/layers/escape", "../layers", "/survey"])
def test_alias_cannot_shadow_inputs(alias):
d = definition()
d["groups"][0]["stage_outputs"]["ortho_semantic_survey"] = {alias: "full_plan"}
with pytest.raises(ValueError):
pipeline.validate_stage_outputs(d)
def test_escape_through_existing_link_refused(tmp_path):
output = tmp_path / "owned"
outside = tmp_path / "outside"
output.mkdir()
outside.mkdir()
(output / "full_plan").symlink_to(outside, target_is_directory=True)
with pytest.raises(ValueError, match="escapes"):
pipeline.stage_output_mounts(output, definition()["groups"][0], "ortho_semantic_survey")
assert not list(outside.iterdir())
def test_unique_publisher_required():
d = definition()
g = d["groups"][0]
g["stages"].append("second")
g["stage_outputs"]["second"] = {"/other": "full_plan"}
with pytest.raises(ValueError, match="multiple"):
pipeline.validate_stage_outputs(d)
def test_shipped_graph_uses_one_semantic_producer_with_measured_duration():
from k1link.simulation.ai_polygon.infrastructure_progress import plan
stages, _ = plan()
assert len(stages) == 90
names = [r["stage"] for r in stages]
assert names.count("ortho_semantic_survey") == 1
assert "ortho_segment" not in names and "semantic_layers" not in names
row = next(r for r in stages if r["stage"] == "ortho_semantic_survey")
assert row["measured"] and row["seconds"] == 251.484
+64
View File
@@ -0,0 +1,64 @@
import base64
import hashlib
import importlib.util
import json
from pathlib import Path
import pytest
spec = importlib.util.spec_from_file_location(
"stage_patch", Path(__file__).resolve().parents[1] / "scripts/stage_simulation_worker_patch.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def fixture(tmp_path):
manifest = {
"source.py": hashlib.sha256(b"old").hexdigest(),
"keep.py": hashlib.sha256(b"keep").hexdigest(),
}
encoded = json.dumps(manifest, sort_keys=True, indent=2).encode()
digest = hashlib.sha256(encoded).hexdigest()
releases = tmp_path / "releases"
base = releases / ("ai-polygon-" + digest[:16])
base.mkdir(parents=True)
(base / "source.py").write_bytes(b"old")
(base / "keep.py").write_bytes(b"keep")
base.with_suffix(".manifest.json").write_bytes(encoded)
recipe = dict(
base_release=digest[:16],
base_manifest_sha256=digest,
overlays={
"source.py": dict(
base64=base64.b64encode(b"new").decode(), sha256=hashlib.sha256(b"new").hexdigest()
)
},
)
return base, recipe
def test_patch_preserves_predecessor_and_every_undeclared_file(tmp_path):
base, recipe = fixture(tmp_path)
result = module.stage(tmp_path, recipe)
new = tmp_path / "releases" / ("ai-polygon-" + result["release"])
assert (base / "source.py").read_bytes() == b"old"
assert (new / "source.py").read_bytes() == b"new"
assert (new / "keep.py").read_bytes() == b"keep"
assert result["changed"] == ["source.py"] and not result["activated"]
with pytest.raises(ValueError, match="already exists"):
module.stage(tmp_path, recipe)
def test_corrupted_predecessor_refuses_before_staging(tmp_path):
base, recipe = fixture(tmp_path)
(base / "keep.py").write_bytes(b"corrupt")
with pytest.raises(ValueError, match="Base file changed"):
module.stage(tmp_path, recipe)
assert len(list((tmp_path / "releases").iterdir())) == 2
@pytest.mark.parametrize("path", ["../outside", "/absolute", "C:/outside", "a\\b"])
def test_escape_rejected(tmp_path, path):
with pytest.raises(ValueError):
module.confined(tmp_path, path)
+36
View File
@@ -0,0 +1,36 @@
"""Whole-scene coverage and overlap ownership, with bounded synthetic geometry."""
import sys
from pathlib import Path
import numpy as np
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'simulation/urban-mapping'),str(ROOT/'simulation/urban-mapping/vector'),str(ROOT/'simulation/ai-polygon')]
from whole_scene import plan_tiles
def test_whole_scene_uses_all_bounds_even_beyond_route():
v=np.array([[x,y,0.] for x in range(0,121,2) for y in range(0,21,2)])
f=[]
for x in range(60):
for y in range(10):
i=x*11+y;f.extend([[i,i+1,i+11],[i+1,i+12,i+11]])
request={'source':{},'model':{}}
result=plan_tiles(request,v,np.array(f))
assert len(result['tiles'])==3
assert result['bounds_xy']==[[0.,0.],[120.,20.]]
assert all(t['status']=='pending' for t in result['tiles'])
assert result['tiles'][-1]['core_bounds'][1][0]==120
assert all(t['job']['views'][0]['size']==[1200,1200] for t in result['tiles'])
def test_overlap_owns_polygons_once_and_retains_xyz():
import pytest
pytest.importorskip("shapely")
from whole_vectors import merge
polygon={'id':'crossing','geometry':{'type':'Polygon','coordinates':[[[38,2,3],[42,2,3],[42,6,3],[38,2,3]]]},'properties':{}}
line={'id':'curb','geometry':{'type':'LineString','coordinates':[[30,1,3],[50,1,3]]},'properties':{}}
tiles=[dict(id='left',core_bounds=[[0,0],[40,40]],status='surveyed'),dict(id='right',core_bounds=[[40,0],[80,40]],status='surveyed')]
result=merge({'tiles':tiles,'bounds_xy':[[0,0],[80,40]]},[(t,dict(features=[polygon,line])) for t in tiles],dict(key='a'*64,identity={'provider_sha256':'b'*64},source={}))
assert sum(f['geometry']['type']=='Polygon' for f in result['features'])==1
lines=[f['geometry']['coordinates'] for f in result['features'] if f['geometry']['type']=='LineString']
assert lines==[[[30.,1.,3.],[40.,1.,3.]],[[40.,1.,3.],[50.,1.,3.]]]
assert result['analysis']['tiles_mapped']==2
+96
View File
@@ -0,0 +1,96 @@
"""Location settings preserve source files, geometry identity and run evidence."""
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from test_ai_polygon import make_world
from test_ai_polygon_realtime import realtime as _realtime
from test_simulation_location_library import project_fixture
from k1link.simulation.ai_polygon.contracts import RunCreate, WorkerWorldCreate, WorldSettings
from k1link.simulation.ai_polygon.world_library import WorldLibrary
from k1link.simulation.ai_polygon.worlds import WorldStore
from k1link.web.ai_polygon_api import build_ai_polygon_router
realtime = _realtime
API = "/api/v1/ai-polygon"
def client_for(root):
app = FastAPI()
app.include_router(build_ai_polygon_router(root))
return TestClient(app)
@pytest.mark.parametrize("kind", ["local", "worker", "project"])
def test_rename_remove_restore_survives_restart_without_rewriting_source(tmp_path, kind):
worlds = WorldStore(tmp_path)
if kind == "project":
worlds, project = project_fixture(tmp_path)
row = worlds.projects.world(project)
elif kind == "worker":
request = WorkerWorldCreate(name="Worker scan", filename="scan.ply", byte_length=1024,
author="test", license="CC0", sha256="b" * 64, collider_sha256="c" * 64,
splat_count=10, settings=WorldSettings(prepared=True))
row = worlds.register_worker_asset(request, "worker-006")
else:
row = make_world(worlds)
identity = row["world_id"]
original = worlds.get(identity)
files = {p: p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()}
with client_for(tmp_path) as client:
response = client.patch(f"{API}/worlds/{identity}", json={"display_name":" Новое имя "})
assert response.status_code == 200
assert response.json()["name"] == "Новое имя"
assert response.json()["sha256"] == original["sha256"]
assert client.patch(f"{API}/worlds/{identity}", json={"removed":True}).status_code == 200
with client_for(tmp_path) as client:
catalog = client.get(f"{API}/catalog").json()
assert not catalog["worlds"]
assert catalog["removed_worlds"][0]["world_id"] == identity
assert catalog["removed_worlds"][0]["name"] == "Новое имя"
assert client.patch(f"{API}/worlds/{identity}", json={"removed":False}).status_code == 200
assert client.get(f"{API}/catalog").json()["worlds"][0]["name"] == "Новое имя"
assert worlds.get(identity) == original
for p, before in files.items():
assert p.read_bytes() == before, p
if kind == "worker":
assert worlds.register_worker_asset(request, "worker-006")["world_id"] == identity
assert len(worlds.list()) == 1
def test_invalid_mutations_and_unknown_scan_have_no_effect(tmp_path):
worlds = WorldStore(tmp_path)
row = make_world(worlds)
with client_for(tmp_path) as client:
for changes in [{}, {"display_name":" "}, {"display_name":"x"*121},
{"display_name":"bad\x00name"}, {"removed":"yes"}, {"sha256":"bad"}]:
assert client.patch(f"{API}/worlds/{row['world_id']}", json=changes).status_code == 422
assert client.patch(f"{API}/worlds/aiworld-{'f'*32}", json={"removed":True}).status_code == 404
assert WorldLibrary(worlds).get(row["world_id"]) == row
def test_active_world_cannot_be_removed_and_removed_world_cannot_start(realtime, tmp_path):
store, hello, run = realtime
identity = run["world"]["world_id"]
with client_for(tmp_path) as client:
assert client.patch(f"{API}/worlds/{identity}", json={"removed":True}).status_code == 409
assert client.patch(f"{API}/worlds/{identity}", json={"display_name":"Renamed"}).status_code == 200
assert store.get(run["run_id"])["world"]["name"] == run["world"]["name"]
store.finish(run["run_id"], hello.instance_id, "stopped", "")
WorldLibrary(store.worlds).update(identity, {"removed":True})
with pytest.raises(RuntimeError, match="удалена"):
store.start(RunCreate(world_id=identity, clock="realtime"), "removed-location")
assert store.active is None
def test_metadata_cannot_follow_symlink(tmp_path):
worlds = WorldStore(tmp_path)
row = make_world(worlds)
library = WorldLibrary(worlds)
outside = tmp_path / "untouched.json"
outside.write_text('{"name":"original"}')
library.metadata.path(row["world_id"]).symlink_to(outside)
with pytest.raises(ValueError, match="regular"):
library.update(row["world_id"], {"removed":True})
assert outside.read_text() == '{"name":"original"}'