Files
planet/backend/tests/test_location_agent_workflow.py
T
linkong 04cebdc504
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.82.0
2026-12-01 18:43:57 +08:00

508 lines
18 KiB
Python

"""Tests for Wikidata/PeeringDB L1 resolvers and Tool-Calling Location Agent."""
from __future__ import annotations
import json
import ssl
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()
def test_nominatim_geocoder_retries_transient_ssl_eof(monkeypatch):
from app.services.location.resolvers import nominatim
calls = {"count": 0}
class _FakeResp:
def raise_for_status(self):
return None
def json(self):
return [{"lat": "35.1495", "lon": "-90.0490", "display_name": "Memphis, TN", "address": {"city": "Memphis", "country": "United States"}}]
def _fake_get(*_args, **_kwargs):
calls["count"] += 1
if calls["count"] == 1:
raise ssl.SSLError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1081)")
return _FakeResp()
monkeypatch.setattr(nominatim.httpx, "get", _fake_get)
geocoder = nominatim.build_default_nominatim_geocoder(
min_interval_seconds=0.0,
retry_backoff_seconds=0.0,
max_retries=2,
)
res = geocoder("Memphis, United States")
assert res is not None
assert res["lat"] == "35.1495"
assert calls["count"] == 2
@pytest.mark.asyncio
async def test_location_agent_recovers_from_geocode_verify_exception(monkeypatch):
from app.services.location import agent_resolver
geo_calls = {"count": 0}
def _flaky_geocoder(place_query: str):
geo_calls["count"] += 1
if geo_calls["count"] == 1:
raise ssl.SSLError("[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1081)")
return {
"lat": "35.1495",
"lon": "-90.0490",
"display_name": place_query,
"city": "Memphis",
"region": "Tennessee",
"country": "United States",
}
monkeypatch.setattr(agent_resolver, "_agent_geocoder", _flaky_geocoder)
monkeypatch.setattr(
agent_resolver,
"safe_web_fetch",
lambda url, **_kwargs: _async_val(
SimpleNamespace(url=url, final_url=url, title="Colossus", text="3231 Paul R Lowry Road, Memphis, Tennessee")
),
)
class _RecoveringProvider:
def __init__(self):
self.turn = 0
self.saw_retryable_error = False
async def analyze(self, req):
self.turn += 1
if self.turn == 1:
return SimpleNamespace(
content="",
tool_calls=[
SimpleNamespace(
id="c1",
name="fetch_source_url",
arguments=json.dumps({"url": "https://example.com/colossus"}),
)
],
)
if self.turn == 2:
return SimpleNamespace(
content="",
tool_calls=[
SimpleNamespace(
id="c2",
name="geocode_verify",
arguments=json.dumps({"place_query": "3231 Paul R Lowry Road, Memphis", "country": "United States"}),
)
],
)
if self.turn == 3:
last_msg = req.messages[-1].content if req.messages else ""
if "geocoder request failed" in str(last_msg):
self.saw_retryable_error = True
return SimpleNamespace(
content="",
tool_calls=[
SimpleNamespace(
id="c3",
name="geocode_verify",
arguments=json.dumps({"place_query": "Memphis, Tennessee", "country": "United States"}),
)
],
)
return SimpleNamespace(
content="",
tool_calls=[
SimpleNamespace(
id="c4",
name="submit_location_result",
arguments=json.dumps(
{
"status": "located",
"facility_name": "Colossus Memphis",
"city": "Memphis",
"region": "Tennessee",
"country": "United States",
"precision": "city",
"geocode_candidate_id": "geo_1",
"citations": ["https://example.com/colossus"],
"confidence": 0.9,
"reasoning": "Recovered after geocode retry",
}
),
)
],
)
provider = _RecoveringProvider()
res, term = await run_controlled_location_agent(
provider_client=provider,
web_search_client=None,
query=LocationQuery(name="Colossus Memphis", country="United States"),
)
assert provider.saw_retryable_error is True
assert term is None
assert len(res.candidates) == 1
assert res.candidates[0].city == "Memphis"
async def _async_val(val):
return val