File size: 13,242 Bytes
7a273d3
 
 
0092d86
7a273d3
 
ea2442a
7a273d3
0092d86
7a273d3
c58d3eb
ea2442a
 
 
 
e2d35c0
ea2442a
e2d35c0
c58d3eb
ea2442a
 
 
 
 
 
 
c58d3eb
 
 
7a273d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221eeed
7a273d3
 
 
 
 
 
 
 
 
 
 
 
 
221eeed
7a273d3
 
 
 
 
 
 
 
 
 
 
 
ea2442a
 
 
 
 
 
 
 
 
 
 
 
221eeed
ea2442a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221eeed
ea2442a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1898c7
 
 
 
 
 
 
ea2442a
 
 
 
b1898c7
ea2442a
 
 
 
 
 
 
 
 
b1898c7
 
 
5a29df5
b1898c7
 
 
ea2442a
 
 
 
 
 
 
e2d35c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea2442a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a273d3
 
 
 
 
 
 
 
 
 
 
 
 
ea2442a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea2442a
 
 
 
 
 
 
7a273d3
 
 
 
 
 
e2d35c0
 
7a273d3
 
 
e2d35c0
 
 
 
 
7a273d3
 
 
 
 
 
 
 
 
 
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea2442a
 
 
 
 
b1898c7
ea2442a
7a273d3
 
 
 
 
ea2442a
 
b1898c7
7a273d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
from __future__ import annotations

import json
import time
from http.client import HTTPConnection
from http.server import ThreadingHTTPServer
from threading import Event, Lock, Thread
from typing import Any
from urllib.error import HTTPError

from world_simulator.api.server import (
    _build_handler,
    _modal_health_urls,
    _ModalHealthTarget,
    _ModalHealthWarmer,
    build_handler,
)
from world_simulator.api.runtime import GameRuntime
from world_simulator.config import (
    ConnectorConfig,
    GameConfig,
    NpcConfig,
    ServerConfig,
    SimulationConfig,
    WorldConfig,
)
from world_simulator.domain import WorldState
from world_simulator.simulation.connectors.base import TickPlan
from world_simulator.simulation.spawning import create_world


def test_snapshot_returns_previous_world_while_tick_is_planning() -> None:
    world = create_world(_config(npc_count=2))
    simulator = _SlowSimulator()
    server = ThreadingHTTPServer(("127.0.0.1", 0), _build_handler(world, simulator))
    port = int(server.server_address[1])
    server_thread = Thread(target=server.serve_forever, daemon=True)
    tick_result: dict[str, Any] = {}
    tick_errors: list[Exception] = []

    def post_tick() -> None:
        try:
            status, payload = _request_json(port, "POST", "/tick", timeout=6)
            tick_result["status"] = status
            tick_result["payload"] = payload
        except Exception as exc:
            tick_errors.append(exc)

    server_thread.start()
    tick_thread = Thread(target=post_tick, daemon=True)

    try:
        tick_thread.start()
        assert simulator.started.wait(timeout=1)

        status, snapshot = _request_json(port, "GET", "/scene/state", timeout=1)

        assert status == 200
        assert snapshot["tick"] == 0
        assert snapshot["simulation"]["tick_in_progress"] is True
        assert snapshot["simulation"]["pending_tick"] == 1

        simulator.release.set()
        tick_thread.join(timeout=2)

        assert not tick_thread.is_alive()
        assert tick_errors == []
        assert tick_result["status"] == 200

        status, snapshot = _request_json(port, "GET", "/scene/state", timeout=1)

        assert status == 200
        assert snapshot["tick"] == 1
        assert snapshot["simulation"]["tick_in_progress"] is False
        assert snapshot["simulation"]["pending_tick"] is None
    finally:
        simulator.release.set()
        server.shutdown()
        server.server_close()
        server_thread.join(timeout=1)


def test_snapshot_triggers_modal_health_warmup() -> None:
    world = create_world(_config(npc_count=2))
    warmer = _FakeHealthWarmer()
    server = ThreadingHTTPServer(
        ("127.0.0.1", 0),
        _build_handler(world, _SlowSimulator(), modal_health_warmer=warmer),
    )
    port = int(server.server_address[1])
    server_thread = Thread(target=server.serve_forever, daemon=True)

    server_thread.start()
    try:
        status, snapshot = _request_json(port, "GET", "/scene/state?warmup=1", timeout=1)

        assert status == 200
        assert snapshot["tick"] == 0
        assert snapshot["simulation"]["models"] == [
            {
                "id": "npc_model",
                "label": "NPC model",
                "model": "test-model",
                "status": "ready",
                "http_status": 200,
            }
        ]
        assert warmer.trigger_count == 1

        status, _ = _request_json(port, "GET", "/health", timeout=1)

        assert status == 200
        assert warmer.trigger_count == 1
    finally:
        server.shutdown()
        server.server_close()
        server_thread.join(timeout=1)


def test_snapshot_without_warmup_query_only_reads_model_status() -> None:
    world = create_world(_config(npc_count=2))
    warmer = _FakeHealthWarmer()
    server = ThreadingHTTPServer(
        ("127.0.0.1", 0),
        _build_handler(world, _SlowSimulator(), modal_health_warmer=warmer),
    )
    port = int(server.server_address[1])
    server_thread = Thread(target=server.serve_forever, daemon=True)

    server_thread.start()
    try:
        status, snapshot = _request_json(port, "GET", "/scene/state", timeout=1)

        assert status == 200
        assert snapshot["simulation"]["models"][0]["status"] == "ready"
        assert warmer.trigger_count == 0
    finally:
        server.shutdown()
        server.server_close()
        server_thread.join(timeout=1)


def test_modal_health_urls_use_only_modal_openai_connectors() -> None:
    config = _config(
        npc_count=2,
        connector=ConnectorConfig(
            type="openai_compatible",
            base_url="https://workspace--npc-serve.modal.run/v1",
            model="npc-model",
        ),
        secondary_connectors={
            "qwen": ConnectorConfig(
                type="openai_compatible",
                base_url="https://workspace--qwen-serve.modal.run/v1/chat/completions",
                model="qwen-model",
            )
        },
    )

    assert _modal_health_urls(config) == [
        "https://workspace--npc-serve.modal.run/health",
        "https://workspace--qwen-serve.modal.run/health",
    ]

    config = _config(
        npc_count=2,
        connector=ConnectorConfig(
            type="openai_compatible",
            base_url="https://workspace--npc-serve.modal.run/v1",
            model="npc-model",
        ),
        secondary_connectors={
            "external": ConnectorConfig(
                type="openai_compatible",
                base_url="https://api.openai.com/v1",
                model="external-model",
            )
        },
    )

    assert _modal_health_urls(config) == [
        "https://workspace--npc-serve.modal.run/health"
    ]


def test_http_server_admin_can_switch_npc_model(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("ADMIN_TOKEN", "test-admin")
    config = _config(
        npc_count=2,
        connector=ConnectorConfig(
            type="openai_compatible",
            base_url="https://workspace--npc-serve.modal.run/v1",
            model="npc-model",
        ),
        secondary_connectors={
            "qwen": ConnectorConfig(
                type="openai_compatible",
                base_url="https://workspace--qwen-serve.modal.run/v1",
                model="qwen-model",
            )
        },
    )
    world = create_world(config)
    runtime = GameRuntime(world=world, simulator=_SlowSimulator(), config=config)
    server = ThreadingHTTPServer(("127.0.0.1", 0), build_handler(runtime))
    port = int(server.server_address[1])
    server_thread = Thread(target=server.serve_forever, daemon=True)

    server_thread.start()
    try:
        status, payload = _request_json(
            port,
            "GET",
            "/admin/models",
            timeout=1,
            headers={"X-Admin-Token": "test-admin"},
        )
        assert status == 200
        assert {profile["id"] for profile in payload["profiles"]} >= {"default", "qwen"}
        qwen_profile = next(profile for profile in payload["profiles"] if profile["id"] == "qwen")
        assert qwen_profile["model"] == "qwen-model"

        status, payload = _request_json(
            port,
            "POST",
            "/admin/npcs/npc-001/model",
            timeout=1,
            headers={"X-Admin-Token": "test-admin"},
            body={"profile_id": "qwen"},
        )

        assert status == 200
        assert payload["profile"]["id"] == "qwen"
        assert world.npcs[0].model_profile_id == "qwen"
        assert world.npcs[0].connector_id == "qwen"
    finally:
        server.shutdown()
        server.server_close()
        server_thread.join(timeout=1)


def test_forced_modal_warmup_does_not_duplicate_inflight_checks() -> None:
    opener = _BlockingOpener()
    warmer = _ModalHealthWarmer(
        [
            _ModalHealthTarget(
                id="npc_model",
                label="NPC model",
                model="test-model",
                health_url="https://workspace--npc-serve.modal.run/health",
            )
        ],
        opener=opener,
    )

    warmer.trigger(force=True)
    assert opener.started.wait(timeout=1)
    warmer.trigger(force=True)

    statuses = warmer.statuses()
    try:
        assert opener.call_count == 1
        assert statuses == [
            {
                "id": "npc_model",
                "label": "NPC model",
                "model": "test-model",
                "status": "checking",
                "http_status": None,
            }
        ]
    finally:
        opener.release.set()


def test_modal_health_warmer_keeps_503_loading_as_warmup_until_ready() -> None:
    opener = _LoadingThenReadyOpener()
    warmer = _ModalHealthWarmer(
        [
            _ModalHealthTarget(
                id="npc_model",
                label="NPC model",
                model="test-model",
                health_url="https://workspace--npc-serve.modal.run/health",
            )
        ],
        warmup_retry_seconds=0.05,
        opener=opener,
    )

    warmer.trigger(force=True)
    assert opener.loading_returned.wait(timeout=1)
    _wait_for_status(warmer, status="warmup", http_status=503)

    opener.allow_ready.set()
    assert opener.ready_returned.wait(timeout=1)
    _wait_for_status(warmer, status="ready", http_status=200)


class _SlowSimulator:
    name = "slow"

    def __init__(self) -> None:
        self.started = Event()
        self.release = Event()

    def propose_tick(self, _world: WorldState, _next_tick: int) -> TickPlan:
        self.started.set()
        self.release.wait(timeout=5)
        return TickPlan(source=self.name, directives=[])


class _FakeHealthWarmer:
    def __init__(self) -> None:
        self.trigger_count = 0

    def trigger(self, *, force: bool = False) -> None:
        self.trigger_count += 1

    def statuses(self) -> list[dict[str, Any]]:
        return [
            {
                "id": "npc_model",
                "label": "NPC model",
                "model": "test-model",
                "status": "ready",
                "http_status": 200,
            }
        ]


class _BlockingOpener:
    def __init__(self) -> None:
        self.started = Event()
        self.release = Event()
        self._lock = Lock()
        self.call_count = 0

    def __call__(self, url: str) -> Any:
        _ = url
        with self._lock:
            self.call_count += 1
        self.started.set()
        self.release.wait(timeout=5)
        return _FakeResponse()


class _LoadingThenReadyOpener:
    def __init__(self) -> None:
        self.loading_returned = Event()
        self.allow_ready = Event()
        self.ready_returned = Event()
        self._lock = Lock()
        self.call_count = 0

    def __call__(self, url: str) -> Any:
        with self._lock:
            self.call_count += 1
            call_count = self.call_count

        if call_count == 1:
            self.loading_returned.set()
            raise HTTPError(url, 503, "Service Unavailable", hdrs=None, fp=None)

        self.allow_ready.wait(timeout=5)
        self.ready_returned.set()
        return _FakeResponse()


class _FakeResponse:
    status: int = 200

    def close(self) -> None:
        return


def _request_json(
    port: int,
    method: str,
    path: str,
    *,
    timeout: float,
    headers: dict[str, str] | None = None,
    body: dict[str, Any] | None = None,
) -> tuple[int, dict[str, Any]]:
    connection = HTTPConnection("127.0.0.1", port, timeout=timeout)
    try:
        request_body = json.dumps(body).encode("utf-8") if body is not None else None
        request_headers = dict(headers or {})
        if request_body is not None:
            request_headers.setdefault("Content-Type", "application/json")
        connection.request(method, path, body=request_body, headers=request_headers)
        response = connection.getresponse()
        body = response.read().decode("utf-8")
    finally:
        connection.close()

    payload = json.loads(body)
    assert isinstance(payload, dict)
    return response.status, payload


def _wait_for_status(
    warmer: _ModalHealthWarmer,
    *,
    status: str,
    http_status: int,
) -> None:
    deadline = time.monotonic() + 1
    while time.monotonic() < deadline:
        statuses = warmer.statuses()
        if (
            statuses[0]["status"] == status
            and statuses[0]["http_status"] == http_status
        ):
            return
        time.sleep(0.01)
    raise AssertionError(f"Expected {status=} and {http_status=}, got {warmer.statuses()!r}")


def _config(
    *,
    npc_count: int,
    connector: ConnectorConfig | None = None,
    god_console: ConnectorConfig | None = None,
    secondary_connectors: dict[str, ConnectorConfig] | None = None,
) -> GameConfig:
    return GameConfig(
        world=WorldConfig(width=80, depth=80, terrain="plain_green", seed=42),
        npcs=NpcConfig(count=npc_count),
        simulation=SimulationConfig(tick_ms=500),
        server=ServerConfig(host="127.0.0.1", port=8000),
        connector=connector or ConnectorConfig(type="deterministic"),
        god_console=god_console,
        secondary_connectors=secondary_connectors or {},
    )