366 lines
13 KiB
Python
366 lines
13 KiB
Python
"""Tests for Wikidata/PeeringDB L1 resolvers and Tool-Calling Location Agent."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from app.db.session import Base
|
|
from app.models.compute_center_location import ComputeCenterLocationRecord
|
|
from app.models.situational_assessment import WorkflowRun
|
|
from app.services.location.agent_resolver import run_controlled_location_agent
|
|
from app.services.location.models import LocationQuery
|
|
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
|
|
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
|
|
|
|
|
|
class _SyncAsAsyncSession:
|
|
def __init__(self, sync_session):
|
|
self._s = sync_session
|
|
|
|
def add(self, obj):
|
|
return self._s.add(obj)
|
|
|
|
async def execute(self, stmt, *args, **kwargs):
|
|
return self._s.execute(stmt, *args, **kwargs)
|
|
|
|
async def scalar(self, stmt, *args, **kwargs):
|
|
return self._s.scalar(stmt, *args, **kwargs)
|
|
|
|
async def get(self, model, ident):
|
|
return self._s.get(model, ident)
|
|
|
|
async def commit(self):
|
|
return self._s.commit()
|
|
|
|
async def rollback(self):
|
|
return self._s.rollback()
|
|
|
|
async def refresh(self, obj):
|
|
return self._s.refresh(obj)
|
|
|
|
async def close(self):
|
|
return self._s.close()
|
|
|
|
|
|
def _make_sync_db():
|
|
engine = create_engine("sqlite:///:memory:")
|
|
Base.metadata.create_all(
|
|
engine,
|
|
tables=[ComputeCenterLocationRecord.__table__, WorkflowRun.__table__],
|
|
)
|
|
sync_factory = sessionmaker(engine, expire_on_commit=False)
|
|
|
|
class _Ctx:
|
|
def __call__(self):
|
|
return self
|
|
|
|
async def __aenter__(self):
|
|
self._sess = _SyncAsAsyncSession(sync_factory())
|
|
return self._sess
|
|
|
|
async def __aexit__(self, *_args):
|
|
await self._sess.close()
|
|
|
|
return engine, _Ctx()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_wikidata_and_peeringdb_resolvers_parse_coordinates(monkeypatch):
|
|
class _FakeResponse:
|
|
def __init__(self, payload):
|
|
self._payload = payload
|
|
|
|
def raise_for_status(self):
|
|
return None
|
|
|
|
def json(self):
|
|
return self._payload
|
|
|
|
class _FakeAsyncClient:
|
|
def __init__(self, **_kwargs):
|
|
pass
|
|
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, *_args):
|
|
return False
|
|
|
|
async def get(self, url, params=None):
|
|
if "wikidata.org" in url and (params or {}).get("action") == "wbsearchentities":
|
|
return _FakeResponse({"search": [{"id": "Q123456"}]})
|
|
if "wikidata.org" in url and (params or {}).get("action") == "wbgetentities":
|
|
return _FakeResponse(
|
|
{
|
|
"entities": {
|
|
"Q123456": {
|
|
"labels": {"en": {"value": "Memphis Supercluster Facility"}},
|
|
"descriptions": {"en": {"value": "data center campus in Memphis, Tennessee"}},
|
|
"claims": {
|
|
"P625": [
|
|
{
|
|
"mainsnak": {
|
|
"datavalue": {
|
|
"value": {"latitude": 35.0612, "longitude": -90.1511}
|
|
}
|
|
}
|
|
}
|
|
]
|
|
},
|
|
}
|
|
}
|
|
}
|
|
)
|
|
if "peeringdb.com" in url:
|
|
return _FakeResponse(
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 9901,
|
|
"name": "Equinix NY5 Secaucus",
|
|
"city": "Secaucus",
|
|
"state": "NJ",
|
|
"country": "US",
|
|
"address1": "800 Secaucus Rd",
|
|
"latitude": 40.7831,
|
|
"longitude": -74.0725,
|
|
}
|
|
]
|
|
}
|
|
)
|
|
return _FakeResponse({})
|
|
|
|
from app.services.location.resolvers import peeringdb_facility, wikidata
|
|
|
|
monkeypatch.setattr(wikidata.httpx, "AsyncClient", _FakeAsyncClient)
|
|
monkeypatch.setattr(peeringdb_facility.httpx, "AsyncClient", _FakeAsyncClient)
|
|
|
|
wd_out = await lookup_wikidata_facility(
|
|
LocationQuery(name="Memphis Supercluster Facility", country="United States")
|
|
)
|
|
assert len(wd_out.candidates) == 1
|
|
assert wd_out.candidates[0].source == "wikidata_facility"
|
|
assert wd_out.candidates[0].latitude == pytest.approx(35.0612, abs=1e-4)
|
|
|
|
pdb_out = await lookup_peeringdb_facility(
|
|
LocationQuery(name="Equinix NY5 Secaucus", country="United States")
|
|
)
|
|
assert len(pdb_out.candidates) == 1
|
|
assert pdb_out.candidates[0].source == "peeringdb_facility"
|
|
assert pdb_out.candidates[0].precision == "precise"
|
|
assert pdb_out.candidates[0].city == "Secaucus"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_tool_calling_location_agent_loop_and_guardrails(monkeypatch):
|
|
from app.services.location import agent_resolver
|
|
|
|
async def _fake_safe_fetch(url, **_kwargs):
|
|
return {
|
|
"url": url,
|
|
"status_code": 200,
|
|
"content": "The Colossus supercomputer operates at 5420 Tulane Rd, Memphis, TN, USA.",
|
|
}
|
|
|
|
def _fake_geocode(place_query, country_hint=""):
|
|
return {
|
|
"latitude": 35.0612,
|
|
"longitude": -90.1511,
|
|
"display_name": "5420 Tulane Rd, Memphis, Shelby County, Tennessee, United States",
|
|
"city": "Memphis",
|
|
"region": "Tennessee",
|
|
"country": "美国",
|
|
"precision": "precise",
|
|
}
|
|
|
|
monkeypatch.setattr(agent_resolver, "safe_web_fetch", _fake_safe_fetch)
|
|
monkeypatch.setattr(agent_resolver, "_agent_geocoder", _fake_geocode)
|
|
|
|
class _StepProvider:
|
|
def __init__(self):
|
|
self.turn = 0
|
|
|
|
async def analyze(self, req):
|
|
self.turn += 1
|
|
if self.turn == 1:
|
|
return SimpleNamespace(
|
|
content="",
|
|
tool_calls=[
|
|
SimpleNamespace(
|
|
id="call_1",
|
|
name="fetch_source_url",
|
|
arguments=json.dumps({"url": "https://epoch.ai/colossus-source"}),
|
|
)
|
|
],
|
|
)
|
|
if self.turn == 2:
|
|
return SimpleNamespace(
|
|
content="",
|
|
tool_calls=[
|
|
SimpleNamespace(
|
|
id="call_2",
|
|
name="geocode_verify",
|
|
arguments=json.dumps({"place_query": "5420 Tulane Rd, Memphis, USA", "country": "United States"}),
|
|
)
|
|
],
|
|
)
|
|
return SimpleNamespace(
|
|
content="",
|
|
tool_calls=[
|
|
SimpleNamespace(
|
|
id="call_3",
|
|
name="submit_location_result",
|
|
arguments=json.dumps(
|
|
{
|
|
"status": "located",
|
|
"facility_name": "Colossus Memphis Campus",
|
|
"city": "Memphis",
|
|
"region": "Tennessee",
|
|
"country": "United States",
|
|
"precision": "precise",
|
|
"geocode_candidate_id": "geo_1",
|
|
"citations": ["https://epoch.ai/colossus-source"],
|
|
"confidence": 0.91,
|
|
"reasoning": "Epoch source confirms 5420 Tulane Rd in Memphis.",
|
|
}
|
|
),
|
|
)
|
|
],
|
|
)
|
|
|
|
engine, factory = _make_sync_db()
|
|
|
|
try:
|
|
async with factory() as session:
|
|
result, term = await run_controlled_location_agent(
|
|
provider_client=_StepProvider(),
|
|
web_search_client=None,
|
|
query=LocationQuery(
|
|
name="Colossus",
|
|
country="United States",
|
|
extra={"source": "epoch_ai_gpu", "source_id": "epoch-colossus", "source_url": "https://epoch.ai/colossus-source"},
|
|
),
|
|
db=session,
|
|
)
|
|
assert term is None
|
|
assert len(result.candidates) == 1
|
|
cand = result.candidates[0]
|
|
assert cand.precision == "precise"
|
|
assert cand.city == "Memphis"
|
|
assert cand.raw_payload["citations"] == ["https://epoch.ai/colossus-source"]
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_tool_calling_agent_rejects_unobserved_citations_and_persists_terminal(monkeypatch):
|
|
from app.services.location import agent_resolver
|
|
|
|
monkeypatch.setattr(agent_resolver, "_agent_geocoder", lambda _q, _c="": {
|
|
"latitude": 35.0612,
|
|
"longitude": -90.1511,
|
|
"display_name": "Memphis, TN, USA",
|
|
"city": "Memphis",
|
|
"country": "美国",
|
|
"precision": "city",
|
|
})
|
|
|
|
class _FabricatedCitationProvider:
|
|
def __init__(self):
|
|
self.turn = 0
|
|
|
|
async def analyze(self, _req):
|
|
self.turn += 1
|
|
if self.turn == 1:
|
|
return SimpleNamespace(
|
|
content="",
|
|
tool_calls=[
|
|
SimpleNamespace(
|
|
id="g1",
|
|
name="geocode_verify",
|
|
arguments=json.dumps({"place_query": "Memphis, USA", "country": "United States"}),
|
|
)
|
|
],
|
|
)
|
|
return SimpleNamespace(
|
|
content="",
|
|
tool_calls=[
|
|
SimpleNamespace(
|
|
id="s1",
|
|
name="submit_location_result",
|
|
arguments=json.dumps(
|
|
{
|
|
"status": "located",
|
|
"geocode_candidate_id": "geo_1",
|
|
"citations": ["https://madeup.example.com/fake-url"],
|
|
"country": "United States",
|
|
"reasoning": "Made up citation test",
|
|
}
|
|
),
|
|
)
|
|
],
|
|
)
|
|
|
|
res_bad, _ = await run_controlled_location_agent(
|
|
provider_client=_FabricatedCitationProvider(),
|
|
web_search_client=None,
|
|
query=LocationQuery(name="FakeCitedCluster", country="United States"),
|
|
)
|
|
assert res_bad.candidates == []
|
|
assert "No verified citation URLs" in (res_bad.failure_reason or "")
|
|
|
|
class _TerminalProvider:
|
|
async def analyze(self, _req):
|
|
return SimpleNamespace(
|
|
content="",
|
|
tool_calls=[
|
|
SimpleNamespace(
|
|
id="t1",
|
|
name="submit_location_result",
|
|
arguments=json.dumps(
|
|
{
|
|
"status": "undisclosed",
|
|
"reasoning": "Customer confidential cluster location is undisclosed.",
|
|
}
|
|
),
|
|
)
|
|
],
|
|
)
|
|
|
|
engine, factory = _make_sync_db()
|
|
|
|
from app.services import compute_center_locations
|
|
|
|
monkeypatch.setattr(
|
|
compute_center_locations,
|
|
"refresh_compute_center_location_cache",
|
|
lambda _db: _noop(),
|
|
)
|
|
|
|
async def _noop():
|
|
return None
|
|
|
|
try:
|
|
async with factory() as session:
|
|
res_term, term = await run_controlled_location_agent(
|
|
provider_client=_TerminalProvider(),
|
|
web_search_client=None,
|
|
query=LocationQuery(
|
|
name="Undisclosed Customer",
|
|
extra={"source": "epoch_ai_gpu", "source_id": "epoch-undisclosed"},
|
|
),
|
|
db=session,
|
|
)
|
|
assert term == "undisclosed"
|
|
assert res_term.candidates == []
|
|
saved = await session.get(ComputeCenterLocationRecord, 1)
|
|
assert saved is not None
|
|
assert saved.verification_status == "undisclosed"
|
|
finally:
|
|
engine.dispose()
|