"""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