Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
313 lines
12 KiB
Python
313 lines
12 KiB
Python
"""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()
|