Files
planet/backend/tests/test_location_agent_workflow.py
T
linkong e1cc27f13d
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.84.0
2026-12-04 07:07:19 +08:00

937 lines
33 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Tests for the true-DAG `location.resolve_unknown` workflow, atomic tools, and guardrails."""
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.ai_workflow import AIWorkflow, AIWorkflowRevision
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.situational_assessment import WorkflowRun
from app.models.system_setting import SystemSetting
from app.services.compute_center_locations import COMPUTE_CENTER_LOCATION_CACHE, _cache_key
from app.services.location import workflow_tools
from app.services.location.models import LocationCandidate, LocationQuery
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
from app.services.location.workflow_tools import run_location_workflow
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=[
AIWorkflow.__table__,
AIWorkflowRevision.__table__,
ComputeCenterLocationRecord.__table__,
SystemSetting.__table__,
WorkflowRun.__table__,
],
)
sync_factory = sessionmaker(engine, expire_on_commit=False)
class _Ctx:
def __call__(self):
return self
async def __aenter__(self):
self._s = sync_factory()
return _SyncAsAsyncSession(self._s)
async def __aexit__(self, exc_type, exc, tb):
self._s.close()
return False
return engine, _Ctx()
async def _async_val(val):
return val
def _stub_empty_l1(monkeypatch):
monkeypatch.setattr(
workflow_tools,
"lookup_wikidata_facility",
lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())),
)
monkeypatch.setattr(
workflow_tools,
"lookup_peeringdb_facility",
lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())),
)
monkeypatch.setattr(
"app.services.compute_center_locations._lookup_ror_organization",
lambda _q: None,
)
@pytest.mark.asyncio
async def test_l0_short_circuits_cached_terminal_without_calling_l1_or_llm(monkeypatch):
key = _cache_key("epoch_ai_gpu", "epoch-term-1")
COMPUTE_CENTER_LOCATION_CACHE[key] = {
"source": "epoch_ai_gpu",
"source_id": "epoch-term-1",
"verification_status": "undisclosed",
"source_note": "Confirmed NDA undisclosed",
}
class _ExplodingAI:
async def analyze(self, _req):
raise AssertionError("LLM must not be called on cached L0 terminal")
try:
res = await run_location_workflow(
db=None,
query=LocationQuery(
name="SecretCluster",
extra={"source": "epoch_ai_gpu", "source_id": "epoch-term-1"},
),
provider_client=_ExplodingAI(),
record_run=False,
)
assert res["success"] is False
assert res["terminal_status"] == "undisclosed"
assert "NDA undisclosed" in (res["failure_reason"] or "")
statuses = {t["node_id"]: t["status"] for t in res["node_traces"]}
assert statuses["l0_normalize"] == "completed"
assert statuses["l1_knowledge"] == "skipped"
assert statuses["l2_judge_r1"] == "skipped"
assert statuses["l4_persist_outcome"] == "completed"
finally:
COMPUTE_CENTER_LOCATION_CACHE.pop(key, None)
@pytest.mark.asyncio
async def test_l1_hit_skips_l2_and_records_single_workflow_run(monkeypatch):
hit = LocationCandidate(
latitude=35.9297,
longitude=-84.3095,
display_name="Oak Ridge National Laboratory",
precision="site",
confidence=0.9,
query="wikidata:Frontier",
source="wikidata_p625",
source_note="Wikidata P625",
matched_fields=("name",),
needs_confirmation=True,
city="Oak Ridge",
country="美国",
)
monkeypatch.setattr(
workflow_tools,
"lookup_wikidata_facility",
lambda _q: _async_val(SimpleNamespace(candidates=(hit,), attempted_queries=("wikidata:Frontier",))),
)
monkeypatch.setattr(
workflow_tools,
"lookup_peeringdb_facility",
lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())),
)
monkeypatch.setattr(
"app.services.compute_center_locations._lookup_ror_organization",
lambda _q: None,
)
class _ExplodingAI:
async def analyze(self, _req):
raise AssertionError("LLM must skip on L1 hit")
engine, factory = _make_sync_db()
try:
async with factory() as session:
res = await run_location_workflow(
db=session,
query=LocationQuery(name="Frontier", country="美国"),
provider_client=_ExplodingAI(),
trigger_evolution=False,
)
assert res["success"] is True
assert res["candidates"][0].city == "Oak Ridge"
assert res["workflow_run_id"]
statuses = {t["node_id"]: t["status"] for t in res["node_traces"]}
assert statuses["l1_knowledge"] == "completed"
assert statuses["l2_research_r1"] == "skipped"
assert statuses["l4_persist_outcome"] == "completed"
run = await session.get(WorkflowRun, res["workflow_run_id"])
assert run is not None
assert run.status == "completed"
assert run.budget_used.get("steps") == 0
finally:
engine.dispose()
@pytest.mark.asyncio
async def test_r1_direct_locate_skips_r2_and_resolves_evidence_ids(monkeypatch):
_stub_empty_l1(monkeypatch)
monkeypatch.setattr(
workflow_tools,
"safe_web_fetch",
lambda url, **_kwargs: _async_val(
SimpleNamespace(
url=url,
final_url=url,
title="Colossus Source",
text="xAI Colossus sits at 5420 Tulane Rd, Memphis, TN, United States.",
)
),
)
monkeypatch.setattr(
workflow_tools,
"_agent_geocoder",
lambda _q: {
"lat": "35.0612",
"lon": "-90.1511",
"display_name": "5420 Tulane Rd, Memphis, TN, USA",
"address": {"house_number": "5420", "road": "Tulane Rd", "city": "Memphis", "country": "United States"},
},
)
class _FakeSearch:
async def search(self, _q, max_results=5):
return []
class _R1AI:
def __init__(self):
self.calls = 0
async def analyze(self, req):
self.calls += 1
items = (req.context or {}).get("evidence_items") or []
assert len(items) == 1
assert items[0]["id"] == "E1"
assert "epoch.ai/colossus-source" in items[0]["url"]
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"facility_name": "xAI Colossus",
"address": "5420 Tulane Rd",
"city": "Memphis",
"region": "Tennessee",
"country": "United States",
"precision": "precise",
"confidence": 0.93,
"evidence_ids": ["E1"],
"reasoning": "E1 confirms Memphis street address.",
}
),
model="test-model",
provider="test-provider",
)
res = await run_location_workflow(
db=None,
query=LocationQuery(
name="Colossus",
country="美国",
extra={
"source": "epoch_ai_gpu",
"source_id": "epoch-colossus",
"source_url": "https://epoch.ai/colossus-source?utm_source=x",
"sources": ["https://epoch.ai/data/gpu-clusters.csv"],
},
),
provider_client=_R1AI(),
web_search_client=_FakeSearch(),
record_run=False,
)
assert res["success"] is True
cand = res["candidates"][0]
assert cand.precision == "precise"
assert cand.city == "Memphis"
assert cand.raw_payload["evidence_ids"] == ["E1"]
assert cand.raw_payload["citations"] == ["https://epoch.ai/colossus-source?utm_source=x"]
statuses = {t["node_id"]: t["status"] for t in res["node_traces"]}
assert statuses["l2_research_r1"] == "completed"
assert statuses["l2_judge_r1"] == "completed"
assert statuses["l2_research_r2"] == "skipped"
assert statuses["l2_judge_r2"] == "skipped"
@pytest.mark.asyncio
async def test_r1_need_followup_triggers_r2_and_cascade_geocodes_city(monkeypatch):
_stub_empty_l1(monkeypatch)
geo_queries = []
def _geocoder(q):
geo_queries.append(q)
if "Mesa Laboratory" in q:
return None
return {
"lat": "39.9784",
"lon": "-105.2749",
"display_name": "Boulder, Colorado, United States",
"address": {"city": "Boulder", "state": "Colorado", "country": "United States"},
}
monkeypatch.setattr(workflow_tools, "_agent_geocoder", _geocoder)
monkeypatch.setattr(
workflow_tools,
"safe_web_fetch",
lambda url, **_kwargs: _async_val(
SimpleNamespace(
url=url,
final_url=url,
title="NCAR DYEUS",
text="IBM GRAF / DYEUS GPU cluster operates inside NCAR Mesa Laboratory, Boulder, Colorado.",
)
),
)
search_queries = []
class _Search:
async def search(self, q, max_results=5):
search_queries.append(q)
if "Boulder" in q:
return [
SimpleNamespace(
title="NCAR Boulder announcement",
url="https://ncar.ucar.edu/dyeus",
snippet="DYEUS is hosted in Boulder, Colorado.",
)
]
return [
SimpleNamespace(
title="IBM Weather Blog",
url="https://blogs.nvidia.com/dyeus-graf",
snippet="IBM weather GPU cluster partnered with NCAR.",
)
]
class _TwoRoundAI:
def __init__(self):
self.calls = 0
async def analyze(self, req):
self.calls += 1
if self.calls == 1:
assert all("美国" not in q for q in search_queries)
return SimpleNamespace(
content=json.dumps(
{
"decision": "need_followup",
"followup_queries": ["IBM DYEUS NCAR Boulder"],
"fetch_urls": ["https://blogs.nvidia.com/dyeus-graf"],
"reasoning": "R1 mentions NCAR, fetch full blog and search Boulder.",
}
),
model="test",
provider="minimax",
)
items = (req.context or {}).get("evidence_items") or []
assert len(items) >= 2
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"facility_name": "NCAR Mesa Laboratory",
"city": "Boulder",
"region": "Colorado",
"country": "United States",
"precision": "site",
"confidence": 0.89,
"evidence_ids": ["E2"],
"reasoning": "R2 confirms NCAR Mesa Laboratory in Boulder, CO.",
}
),
model="test",
provider="minimax",
)
ai = _TwoRoundAI()
res = await run_location_workflow(
db=None,
query=LocationQuery(
name="IBM DYEUS",
country="美国",
extra={"operator": "IBM", "source": "epoch_ai_gpu", "source_id": "epoch_ibm_dyeus"},
),
provider_client=ai,
web_search_client=_Search(),
record_run=False,
)
assert ai.calls == 2
assert any("IBM DYEUS NCAR Boulder" == q for q in search_queries)
assert any("Mesa Laboratory" in q for q in geo_queries)
assert "Boulder, Colorado, United States" in geo_queries
assert res["success"] is True
assert res["candidates"][0].city == "Boulder"
assert res["candidates"][0].precision == "city" # downgraded because geocoder returned city level
statuses = {t["node_id"]: t["status"] for t in res["node_traces"]}
assert statuses["l2_research_r2"] == "completed"
assert statuses["l2_judge_r2"] == "completed"
@pytest.mark.asyncio
async def test_r2_coerces_need_followup_to_unresolved(monkeypatch):
_stub_empty_l1(monkeypatch)
class _Search:
async def search(self, _q, max_results=5):
return [SimpleNamespace(title="Partial", url="https://example.com/partial", snippet="Vague mention")]
class _StubbornAI:
async def analyze(self, _req):
return SimpleNamespace(
content=json.dumps(
{
"decision": "need_followup",
"followup_queries": ["more searches"],
"reasoning": "Still unsure.",
}
),
model="test",
provider="test",
)
res = await run_location_workflow(
db=None,
query=LocationQuery(name="VagueCluster", country="France"),
provider_client=_StubbornAI(),
web_search_client=_Search(),
record_run=False,
)
assert res["success"] is False
assert "Still unsure." in (res["failure_reason"] or "")
@pytest.mark.asyncio
async def test_terminal_status_rejected_without_evidence_and_persisted_with_evidence(monkeypatch):
_stub_empty_l1(monkeypatch)
monkeypatch.setattr(
"app.services.compute_center_locations.refresh_compute_center_location_cache",
lambda _db: _async_val(None),
)
class _UndisclosedAI:
async def analyze(self, _req):
return SimpleNamespace(
content=json.dumps(
{
"decision": "undisclosed",
"evidence_ids": ["E1"],
"reasoning": "Confirmed customer confidential NDA.",
}
),
model="test",
provider="test",
)
class _EmptySearch:
async def search(self, _q, max_results=5):
return []
class _HitSearch:
async def search(self, _q, max_results=5):
return [SimpleNamespace(title="NDA", url="https://example.com/nda", snippet="Undisclosed customer facility")]
engine, factory = _make_sync_db()
try:
async with factory() as session:
bad = await run_location_workflow(
db=session,
query=LocationQuery(
name="SecretA",
extra={"source": "epoch_ai_gpu", "source_id": "epoch-secret-a"},
),
provider_client=_UndisclosedAI(),
web_search_client=_EmptySearch(),
trigger_evolution=False,
)
assert bad["terminal_status"] is None
assert "without tool evidence" in (bad["failure_reason"] or "")
good = await run_location_workflow(
db=session,
query=LocationQuery(
name="SecretB",
extra={"source": "epoch_ai_gpu", "source_id": "epoch-secret-b"},
),
provider_client=_UndisclosedAI(),
web_search_client=_HitSearch(),
trigger_evolution=False,
)
assert good["terminal_status"] == "undisclosed"
saved = await session.get(ComputeCenterLocationRecord, 1)
assert saved is not None
assert saved.verification_status == "undisclosed"
finally:
engine.dispose()
@pytest.mark.asyncio
async def test_guardrail_rejects_state_level_below_min_confidence_and_unobserved_urls(monkeypatch):
_stub_empty_l1(monkeypatch)
class _Search:
async def search(self, _q, max_results=5):
return [SimpleNamespace(title="Iowa DC", url="https://example.com/iowa", snippet="Iowa")]
monkeypatch.setattr(
workflow_tools,
"_agent_geocoder",
lambda _q: {
"lat": "41.878",
"lon": "-93.0977",
"display_name": "Iowa, United States",
"address": {"state": "Iowa", "country": "United States"},
},
)
class _StateAI:
async def analyze(self, _req):
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"city": "Iowa",
"country": "United States",
"precision": "city",
"confidence": 0.85,
"evidence_ids": ["E1"],
"reasoning": "Only state level found.",
}
)
)
res_state = await run_location_workflow(
db=None,
query=LocationQuery(name="StateCluster", country="United States"),
provider_client=_StateAI(),
web_search_client=_Search(),
record_run=False,
)
assert res_state["success"] is False
assert "only country or region/state level" in (res_state["failure_reason"] or "")
monkeypatch.setattr(
workflow_tools,
"_agent_geocoder",
lambda _q: {
"lat": "41.5868",
"lon": "-93.625",
"display_name": "Des Moines, IA, USA",
"address": {"city": "Des Moines", "country": "United States"},
},
)
class _FakeCiteAI:
async def analyze(self, _req):
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"city": "Des Moines",
"country": "United States",
"precision": "city",
"confidence": 0.9,
"evidence_ids": ["E99"],
"citations": ["https://fake.example.invalid/madeup"],
"reasoning": "Fabricated URL.",
}
)
)
res_fake = await run_location_workflow(
db=None,
query=LocationQuery(name="FakeCite", country="United States"),
provider_client=_FakeCiteAI(),
web_search_client=_Search(),
record_run=False,
)
assert res_fake["success"] is False
assert "No verified citation URLs" in (res_fake["failure_reason"] or "")
class _LowConfAI:
async def analyze(self, _req):
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"city": "Des Moines",
"country": "United States",
"precision": "city",
"confidence": 0.42,
"evidence_ids": ["E1"],
"reasoning": "Weak guess.",
}
)
)
res_low = await run_location_workflow(
db=None,
query=LocationQuery(name="LowConf", country="United States"),
provider_client=_LowConfAI(),
web_search_client=_Search(),
record_run=False,
)
assert res_low["success"] is False
assert "below minimum 0.55" in (res_low["failure_reason"] or "")
@pytest.mark.asyncio
async def test_guardrail_cross_country_override_iseg2_pattern_and_evolution_hook(monkeypatch):
_stub_empty_l1(monkeypatch)
monkeypatch.setattr(
workflow_tools,
"_agent_geocoder",
lambda _q: {
"lat": "64.0025",
"lon": "-22.5594",
"display_name": "Keflavik, Iceland",
"address": {"city": "Keflavik", "country": "Iceland"},
},
)
evo_calls = []
monkeypatch.setattr(
"app.services.ai.workflow_evolver.schedule_post_run_evolution",
lambda wf_id, run_id: evo_calls.append((wf_id, run_id)),
)
class _Search:
async def search(self, _q, max_results=5):
return [SimpleNamespace(title="ISEG2", url="https://verneglobal.com/iseg2", snippet="Keflavik, Iceland")]
class _NoReasonAI:
async def analyze(self, _req):
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"city": "Keflavik",
"country": "Iceland",
"precision": "city",
"confidence": 0.9,
"evidence_ids": ["E1"],
"reasoning": "Found in Keflavik.",
}
)
)
res_blocked = await run_location_workflow(
db=None,
query=LocationQuery(name="ISEG2", country="荷兰"),
provider_client=_NoReasonAI(),
web_search_client=_Search(),
record_run=False,
)
assert res_blocked["success"] is False
assert "Country mismatch" in (res_blocked["failure_reason"] or "")
class _OverrideAI:
async def analyze(self, _req):
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"facility_name": "Verne Global Campus",
"city": "Keflavik",
"country": "Iceland",
"precision": "city",
"confidence": 0.92,
"evidence_ids": ["E1"],
"country_override_reason": "TOP500 lists Nebius HQ NL; facility operates in Iceland.",
"reasoning": "Confirmed Verne Global colocation in Keflavik.",
}
),
model="MiniMax-M3.1-Flash",
provider="minimax",
)
engine, factory = _make_sync_db()
try:
async with factory() as session:
res_ok = await run_location_workflow(
db=session,
query=LocationQuery(name="ISEG2", country="荷兰", extra={"source_id": "top500_13"}),
provider_client=_OverrideAI(),
web_search_client=_Search(),
trigger_evolution=True,
)
assert res_ok["success"] is True
cand = res_ok["candidates"][0]
assert cand.country == "冰岛"
assert cand.raw_payload["country_mismatch_override"]["resolved_country"] == "冰岛"
assert evo_calls == [("location.resolve_unknown", res_ok["workflow_run_id"])]
run = await session.get(WorkflowRun, res_ok["workflow_run_id"])
assert run is not None
assert run.status == "completed"
assert run.budget_used.get("steps") == 1
assert isinstance(run.budget_used.get("node_traces"), list)
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_wikidata_skips_p17_country_mismatch(monkeypatch):
from app.services.location.resolvers import wikidata
class _Resp:
def __init__(self, payload):
self._payload = payload
def raise_for_status(self):
return None
def json(self):
return self._payload
class _Client:
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):
action = (params or {}).get("action")
if action == "wbsearchentities":
return _Resp({"search": [{"id": "Q111"}]})
ids = str((params or {}).get("ids") or "")
if ids == "Q111":
return _Resp(
{
"entities": {
"Q111": {
"labels": {"en": {"value": "Fugaku supercomputer"}},
"descriptions": {"en": {"value": "Japanese supercomputer"}},
"claims": {
"P17": [{"mainsnak": {"datavalue": {"value": {"id": "Q17"}}}}],
"P625": [{"mainsnak": {"datavalue": {"value": {"latitude": 34.653, "longitude": 135.220}}}}],
},
}
}
}
)
return _Resp({"entities": {"Q17": {"labels": {"en": {"value": "Japan"}, "zh": {"value": "日本"}}}}})
monkeypatch.setattr(wikidata.httpx, "AsyncClient", _Client)
out = await lookup_wikidata_facility(LocationQuery(name="Fugaku", country="United States"))
assert not out.candidates
@pytest.mark.asyncio
async def test_peeringdb_skips_generic_operator_only(monkeypatch):
from app.services.location.resolvers import peeringdb_facility
class _ExplodingClient:
def __init__(self, **_kwargs):
raise AssertionError("PeeringDB HTTP client must not run for generic operator only")
monkeypatch.setattr(peeringdb_facility.httpx, "AsyncClient", _ExplodingClient)
out = await lookup_peeringdb_facility(
LocationQuery(name="Nebius", country="Netherlands", extra={"operator": "Nebius"})
)
assert not out.candidates
assert not out.attempted_queries
def test_nominatim_geocoder_requests_english_locale(monkeypatch):
from app.services.location.resolvers import nominatim
captured: dict[str, Any] = {}
class _FakeResp:
def raise_for_status(self):
return None
def json(self):
return [{"lat": "64.0005", "lon": "-22.5583", "display_name": "Keflavik, Iceland", "address": {"city": "Keflavik", "country": "Iceland", "country_code": "is"}}]
def _fake_get(url, *, params=None, headers=None, timeout=None):
captured["url"] = url
captured["params"] = dict(params or {})
captured["headers"] = dict(headers or {})
captured["timeout"] = timeout
return _FakeResp()
monkeypatch.setattr(nominatim.httpx, "get", _fake_get)
geocoder = nominatim.build_default_nominatim_geocoder(min_interval_seconds=0.0, max_retries=0)
res = geocoder("Keflavik, Iceland")
assert res is not None
assert captured["params"].get("accept-language") == "en"
assert captured["headers"].get("Accept-Language") == "en"
@pytest.mark.asyncio
async def test_geocode_verify_accepts_native_country_name_and_country_code(monkeypatch):
from app.services.location import workflow_tools
cases = [
(
"Keflavik, Iceland",
"冰岛",
{"lat": "64.0005", "lon": "-22.5583", "address": {"town": "Keflavik", "country": "Ísland", "country_code": "is"}},
"冰岛",
),
(
"Zurich, Switzerland",
"瑞士",
{"lat": "47.3769", "lon": "8.5417", "address": {"city": "Zürich", "country": "Schweiz/Suisse/Svizzera/Svizra", "country_code": "ch"}},
"瑞士",
),
(
"Abu Dhabi, UAE",
"阿联酋",
{"lat": "24.4539", "lon": "54.3773", "address": {"city": "Abu Dhabi", "country": "الإمارات العربية المتحدة", "country_code": "ae"}},
"阿联酋",
),
(
"Hong Kong",
"中国(香港)",
{"lat": "22.3193", "lon": "114.1694", "address": {"city": "Hong Kong", "country": "Hong Kong", "country_code": "cn"}},
"中国(香港)",
),
]
for place_query, expected_country, fake_payload, expected_canonical in cases:
monkeypatch.setattr(workflow_tools, "_agent_geocoder", lambda _q, p=fake_payload: p)
res, entry = await workflow_tools._geocode_verify_single(place_query, expected_country)
assert entry is not None, f"expected match for {place_query}, got {res}"
assert entry["country"] == expected_canonical
monkeypatch.setattr(
workflow_tools,
"_agent_geocoder",
lambda _q: {"lat": "52.5200", "lon": "13.4050", "address": {"city": "Berlin", "country": "Germany", "country_code": "de"}},
)
res, entry = await workflow_tools._geocode_verify_single("Berlin, Germany", "冰岛")
assert entry is None
assert "Country mismatch" in str(res.get("reason"))
def test_interpret_geocode_result_uses_country_code_for_native_names():
from app.services.location.resolvers.nominatim import interpret_geocode_result
interpreted = interpret_geocode_result(
{
"lat": "64.0005",
"lon": "-22.5583",
"address": {"town": "Keflavik", "country": "Ísland", "country_code": "is"},
},
matched_fields=("city",),
context_country="冰岛",
)
assert interpreted is not None
lat, lon, _addr, classification = interpreted
assert lat == pytest.approx(64.0005)
assert lon == pytest.approx(-22.5583)
assert classification == "city"
def test_sanitize_user_facing_reasoning_strips_evidence_ids_and_preserves_clean_text():
from app.services.location.workflow_tools import sanitize_user_facing_reasoning
assert (
sanitize_user_facing_reasoning(
"E6 confirms DYEUS is IBM's system, while E1-E5 and E11–E14 list other sites (E3)."
)
== "confirms DYEUS is IBM's system, while and list other sites."
)
assert (
sanitize_user_facing_reasoning("官方披露该集群采用多地分布式部署(E1、E2),无法单点落位。")
== "官方披露该集群采用多地分布式部署,无法单点落位。"
)
assert (
sanitize_user_facing_reasoning("NVIDIA H100 EC2 集群部署于美国俄亥俄州都柏林。")
== "NVIDIA H100 EC2 集群部署于美国俄亥俄州都柏林。"
)
def test_upgrade_untouched_location_judge_prompts_preserves_custom_edits():
import copy
from app.models.ai_workflow import AIWorkflow
from app.services.ai.workflow_registry import (
BUILTIN_WORKFLOWS,
_PREV_LOC_JUDGE_PROMPTS,
_upgrade_untouched_location_judge_prompts,
)
spec = next(w for w in BUILTIN_WORKFLOWS if w["workflow_id"] == "location.resolve_unknown")
stock_graph = copy.deepcopy(spec["graph"])
for node in stock_graph["nodes"]:
nid = node["id"]
if nid == "l2_judge_r1":
node["system_prompt"] = _PREV_LOC_JUDGE_PROMPTS["l2_judge_r1"]
elif nid == "l2_judge_r2":
node["system_prompt"] = "CUSTOM USER PROMPT MUST STAY"
row = AIWorkflow(workflow_id="location.resolve_unknown", name="loc", published_graph=stock_graph)
changed = _upgrade_untouched_location_judge_prompts(row, spec)
assert changed is True
nodes_by_id = {n["id"]: n for n in row.published_graph["nodes"]}
assert "严禁出现 E1" in nodes_by_id["l2_judge_r1"]["system_prompt"]
assert nodes_by_id["l2_judge_r2"]["system_prompt"] == "CUSTOM USER PROMPT MUST STAY"