release: bump version to 0.75.0
This commit is contained in:
1 parent
60eefb19c9
commit
5bfc790dec
209 files changed
+13747
-1611
No files matched your search
@@ -0,0 +1,72 @@
|
||||
from datetime import UTC, datetime
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.api.v1.auth import router
|
||||
from app.core import security
|
||||
from app.db.session import DEFAULT_LOGIN_USERS, get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserRegister
|
||||
|
||||
|
||||
async def identity_request(monkeypatch, user, token=None):
|
||||
result = MagicMock()
|
||||
result.scalar_one_or_none.return_value = user
|
||||
db = AsyncMock()
|
||||
db.execute.return_value = result
|
||||
monkeypatch.setattr(security.redis_client, "sismember", lambda *_: False)
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/auth")
|
||||
|
||||
async def override_db():
|
||||
yield db
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
||||
) as client:
|
||||
return await client.get(
|
||||
"/auth/me",
|
||||
headers={"Authorization": "Bearer " + (token or security.create_access_token({"sub": 1}))},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("default", DEFAULT_LOGIN_USERS)
|
||||
async def test_default_identity_preserves_profile_fields(monkeypatch, default):
|
||||
created = datetime(2026, 9, 21, tzinfo=UTC)
|
||||
user = User(
|
||||
id=1, username=default["username"], email=default["email"],
|
||||
role=default["role"], password_hash="not-exposed", is_active=True,
|
||||
email_verified=True, gatekeeper_groups=["ops"], created_at=created,
|
||||
)
|
||||
response = await identity_request(monkeypatch, user)
|
||||
assert response.status_code == 200
|
||||
payload = response.json()
|
||||
assert payload["email"] == default["email"]
|
||||
assert payload["email_verified"] is True
|
||||
assert datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00")) == created
|
||||
assert payload["gatekeeper_groups"] == ["ops"]
|
||||
assert "password_hash" not in payload
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("user", [None, User(id=1, is_active=False)])
|
||||
async def test_missing_or_inactive_identity_is_rejected(monkeypatch, user):
|
||||
response = await identity_request(monkeypatch, user)
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_token_is_not_an_access_identity(monkeypatch):
|
||||
response = await identity_request(monkeypatch, None, security.create_refresh_token({"sub": 1}))
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_registration_still_validates_email():
|
||||
with pytest.raises(ValidationError):
|
||||
UserRegister(username="newuser", email="newuser@planet.local", password="example-password")
|
||||
@@ -79,7 +79,8 @@ class TestTOP500Collector:
|
||||
"""Test parsing empty response"""
|
||||
collector = TOP500Collector()
|
||||
result = collector.parse_response("<html><body><table></table></body></html>")
|
||||
assert len(result) > 0
|
||||
assert result == []
|
||||
assert collector.fail_on_empty
|
||||
|
||||
def test_parse_response_single_item(self):
|
||||
"""Test parsing single item response"""
|
||||
@@ -97,9 +98,9 @@ class TestTOP500Collector:
|
||||
</tr>
|
||||
</table>
|
||||
"""
|
||||
result = collector.parse_response(response)
|
||||
result = collector.parse_response(response, "https://top500.org/lists/top500/2025/11/")
|
||||
assert len(result) == 1
|
||||
assert result[0]["source_id"] == "top500_1"
|
||||
assert result[0]["source_id"] == "top500_system_1"
|
||||
assert result[0]["name"] == "Test Supercomputer"
|
||||
assert result[0]["country"] == "USA"
|
||||
assert result[0]["metadata"]["rank"] == 1
|
||||
@@ -113,7 +114,7 @@ class TestTOP500Collector:
|
||||
<tr><th>Rank</th><th>System</th><th>Cores</th><th>Rmax</th><th>Rpeak</th><th>Power</th></tr>
|
||||
<tr>
|
||||
<td>1</td>
|
||||
<td>Valid\nVendor\nSite\nUSA</td>
|
||||
<td><a href="/system/2/">Valid</a>\nVendor\nSite\nUSA</td>
|
||||
<td>1000</td>
|
||||
<td>10 PFLOP/s</td>
|
||||
<td>12 PFLOP/s</td>
|
||||
@@ -129,7 +130,7 @@ class TestTOP500Collector:
|
||||
</tr>
|
||||
</table>
|
||||
"""
|
||||
result = collector.parse_response(response)
|
||||
result = collector.parse_response(response, "https://top500.org/lists/top500/2025/11/")
|
||||
assert len(result) == 1
|
||||
assert result[0]["name"] == "Valid"
|
||||
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
import csv
|
||||
import io
|
||||
from datetime import UTC, datetime
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
from app.api.v1.compute_intelligence import sample_query, selected_countries
|
||||
from app.services.collectors.epoch_ai import EpochAIGPUCollector
|
||||
from app.services.collectors.top500 import TOP500Collector
|
||||
from app.services.compute_history import compute_history
|
||||
|
||||
|
||||
def epoch_csv(**overrides):
|
||||
row = {
|
||||
"Name": "Cluster Alpha",
|
||||
"Country": "United States of America",
|
||||
"Status": "Existing",
|
||||
"First Operational Date": "2023-05-02",
|
||||
"16-bit OP/s (log)": "18",
|
||||
"Location": "3231 Riverport Rd, Memphis, TN 38109",
|
||||
"latitude": "35",
|
||||
"longitude": "-90",
|
||||
**overrides,
|
||||
}
|
||||
output = io.StringIO()
|
||||
writer = csv.DictWriter(output, fieldnames=list(row))
|
||||
writer.writeheader()
|
||||
writer.writerow(row)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def test_epoch_csv_preserves_precision_date_and_missing_values():
|
||||
collector = EpochAIGPUCollector()
|
||||
row = collector.parse_response(epoch_csv())[0]
|
||||
assert row["value"] == 1e18
|
||||
assert row["unit"] == "FLOP/s"
|
||||
assert row["metadata"]["precision"] == "FP16"
|
||||
assert row["metadata"]["location_precision"] == "precise"
|
||||
assert row["metadata"]["raw_country"] == "United States of America"
|
||||
assert row["reference_date"] == "2023-05-02"
|
||||
missing = collector.parse_response(
|
||||
epoch_csv(**{"16-bit OP/s (log)": "", "First Operational Date": ""})
|
||||
)[0]
|
||||
assert missing["value"] is None
|
||||
assert missing["reference_date"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("location", "country", "expected"),
|
||||
[
|
||||
("United States of America", "United States of America", "country"),
|
||||
("Japan", "Japan", "country"),
|
||||
("Korea (Republic of)", "South Korea", "country"),
|
||||
("Texas", "United States of America", "region"),
|
||||
("Iowa, USA", "United States of America", "region"),
|
||||
("Seoul", "South Korea", "city"),
|
||||
("Paris, France", "France", "city"),
|
||||
("Skolkovo Innovation Center\nMoscow Oblast\nRussia", "Russia", "site"),
|
||||
("Cluster 2, Texas", "United States of America", "site"),
|
||||
("Campus 7, Tokyo", "Japan", "site"),
|
||||
("Building 240, Argonne", "United States of America", "site"),
|
||||
("7", "United States of America", "unknown"),
|
||||
("Jülich Supercomputing Centre\n52428 Jülich, Germany", "Germany", "precise"),
|
||||
("35.380924,139.625008", "Japan", "precise"),
|
||||
('33°24\'28.7"N 112°21\'54.3"W', "United States of America", "precise"),
|
||||
("latitude: 35.0 longitude: 181.0", "United States of America", "unknown"),
|
||||
('99°99\'00"N 200°00\'00"W', "United States of America", "unknown"),
|
||||
("3231 Riverport Rd, Memphis, TN 38109", "United States of America", "precise"),
|
||||
],
|
||||
)
|
||||
def test_epoch_location_precision_follows_location_field(location, country, expected):
|
||||
row = EpochAIGPUCollector().parse_response(
|
||||
epoch_csv(Location=location, Country=country)
|
||||
)[0]
|
||||
|
||||
assert row["metadata"]["location_precision"] == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("location", "expected"),
|
||||
[
|
||||
({"lat": 35.0, "lng": 139.0}, "precise"),
|
||||
({"latitude": 35.0, "longitude": 181.0}, "unknown"),
|
||||
({"lat": 35.0}, "unknown"),
|
||||
({"lng": 139.0}, "unknown"),
|
||||
({"lat": "invalid", "lng": 139.0}, "unknown"),
|
||||
],
|
||||
)
|
||||
def test_epoch_coordinate_object_requires_complete_valid_pair(location, expected):
|
||||
from app.services.epoch_location import assess_epoch_location
|
||||
|
||||
assert assess_epoch_location(location).precision == expected
|
||||
|
||||
|
||||
def test_epoch_anonymous_rows_are_not_geocoded():
|
||||
row = EpochAIGPUCollector().parse_response(epoch_csv(Name="Anonymized 1", Country="China"))[0]
|
||||
assert row["latitude"] is None and row["longitude"] is None
|
||||
assert row["metadata"]["anonymous"] and row["metadata"]["rounded"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
["<html>blocked</html>", "Name,Country\nA,US", epoch_csv(**{"16-bit OP/s (log)": "nan"})],
|
||||
)
|
||||
def test_epoch_invalid_payload_fails_closed(payload):
|
||||
with pytest.raises(ValueError):
|
||||
EpochAIGPUCollector().parse_response(payload)
|
||||
|
||||
|
||||
def test_epoch_duplicate_identity_rejected():
|
||||
payload = epoch_csv()
|
||||
with pytest.raises(ValueError, match="identity collision"):
|
||||
EpochAIGPUCollector().parse_response(payload + payload.splitlines()[1] + "\n")
|
||||
|
||||
|
||||
def test_anonymous_source_rows_preserve_multiplicity_without_claiming_identity():
|
||||
payload = epoch_csv(Name="Anonymized Chinese System", Country="China")
|
||||
rows = EpochAIGPUCollector().parse_response(payload + payload.splitlines()[1] + "\n")
|
||||
assert len(rows) == 2
|
||||
assert rows[0]["source_id"] != rows[1]["source_id"]
|
||||
assert all(row["metadata"]["identity_scope"] == "snapshot_record" for row in rows)
|
||||
|
||||
|
||||
def test_top500_units_and_stable_identity():
|
||||
collector = TOP500Collector()
|
||||
html = '<table id="top500"><tr><th>Rank</th><th>System</th><th>Cores</th><th>Rmax [TFlop/s]</th><th>Rpeak [PFlop/s]</th><th>Power</th></tr><tr><td>{rank}</td><td><a href="/system/123/">Test</a><br>Lab<br>USA</td><td>10</td><td>1,500</td><td>2</td><td>1</td></tr></table>'
|
||||
first = collector.parse_response(
|
||||
html.format(rank=1), "https://top500.org/lists/top500/2025/11/"
|
||||
)[0]
|
||||
second = collector.parse_response(
|
||||
html.format(rank=2), "https://top500.org/lists/top500/2026/06/"
|
||||
)[0]
|
||||
assert first["source_id"] == second["source_id"] == "top500_system_123"
|
||||
assert float(first["value"]) == 1.5e15
|
||||
assert first["metadata"]["rpeak_flops"] == 2e15
|
||||
assert first["reference_date"] == "2025-11-01"
|
||||
assert second["reference_date"] == "2026-06-01"
|
||||
with pytest.raises(ValueError, match="date missing"):
|
||||
collector.parse_response(html.format(rank=1))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_large_source_loss_does_not_create_snapshot():
|
||||
db = AsyncMock()
|
||||
db.scalar.return_value = 500
|
||||
db.add = MagicMock()
|
||||
with pytest.raises(ValueError, match="40%"):
|
||||
await TOP500Collector()._create_snapshot(db, 1, [{}] * 2, datetime.now(UTC))
|
||||
db.add.assert_not_called()
|
||||
db.commit.assert_not_awaited()
|
||||
|
||||
|
||||
def test_history_missing_years_and_denominators():
|
||||
global_data = compute_history(["CN", "US"])
|
||||
assert global_data["compute"][3]["values"] == {"CN": 31, "US": 41}
|
||||
assert global_data["compute"][-1]["values"] == {"CN": None, "US": None}
|
||||
bilateral = compute_history(["CN", "US"], "bilateral_share")
|
||||
assert sum(bilateral["compute"][3]["values"].values()) == 100
|
||||
assert bilateral["denominator"] == "US+CN"
|
||||
absolute = compute_history(["US", "CN"], "absolute")
|
||||
assert absolute["compute"][3]["values"] == {"US": None, "CN": 435}
|
||||
assert global_data["innovation"][-2]["value"] == 17.95
|
||||
assert global_data["innovation"][-1]["value"] is None
|
||||
assert global_data["evidence"]["innovation-2026"]["published_at"] == "2026-07-17"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_snapshot_query_uses_observation_cutoff_not_location():
|
||||
query = await sample_query(AsyncMock(), ["CN"], 2023)
|
||||
sql = str(query.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}))
|
||||
assert "2024-01-01" in sql
|
||||
assert "row_number() OVER (PARTITION BY" in sql
|
||||
assert "compute_contract" in sql and "中国" in sql
|
||||
assert "latitude" not in sql and "longitude" not in sql
|
||||
|
||||
|
||||
def test_country_input_is_bounded_and_deduplicated():
|
||||
assert selected_countries("CN,CN,US") == ["CN", "US"]
|
||||
assert selected_countries("CN,US,EUROPE,APAC,OTHER")[-1] == "OTHER"
|
||||
with pytest.raises(HTTPException):
|
||||
selected_countries("invalid")
|
||||
with pytest.raises(HTTPException, match="overlapping"):
|
||||
selected_countries("EUROPE,DE")
|
||||
|
||||
|
||||
def test_catalog_supports_global_participants_without_inventing_history():
|
||||
from app.services.compute_catalog import (
|
||||
CATALOG,
|
||||
COMPARISON_GROUPS,
|
||||
COUNTRIES,
|
||||
source_country_names,
|
||||
source_country_participants,
|
||||
)
|
||||
|
||||
assert {"CN", "US", "JP", "KR", "IN", "DE", "FR", "GB", "AU", "BR", "ZA"}.issubset(
|
||||
{entry["code"] for entry in CATALOG}
|
||||
)
|
||||
assert not {"TW", "HK", "MO", "XK"}.intersection(entry["code"] for entry in CATALOG)
|
||||
owners = source_country_names(["CN"])
|
||||
assert {"中国", "中国(台湾)", "中国(香港)", "中国(澳门)"}.issubset(owners)
|
||||
assert source_country_participants(["CN"])["中国(台湾)"] == "CN"
|
||||
assert [entry["code"] for entry in CATALOG[:5]] == ["CN", "US", "EUROPE", "APAC", "OTHER"]
|
||||
assert [entry["kind"] for entry in CATALOG[:5]] == [
|
||||
"country",
|
||||
"country",
|
||||
"region",
|
||||
"region",
|
||||
"region",
|
||||
]
|
||||
group_members = [
|
||||
member
|
||||
for _code, _name, _name_en, members, _anchor in COMPARISON_GROUPS
|
||||
for member in members
|
||||
]
|
||||
assert len(group_members) == len(set(group_members))
|
||||
assert set(group_members) == set(COUNTRIES)
|
||||
data = compute_history(["JP", "KR"])
|
||||
assert [row["values"]["JP"] for row in data["compute"][:4]] == [6, 5, 4, 4]
|
||||
assert all(row["values"]["KR"] is None for row in data["compute"])
|
||||
assert all(row["value"] is None for row in data["innovation"])
|
||||
assert len(data["catalog"]) > 30
|
||||
|
||||
|
||||
def test_region_history_requires_complete_same_year_member_coverage():
|
||||
data = compute_history(["CN", "US", "EUROPE", "APAC", "OTHER"])
|
||||
row_2023 = next(row for row in data["compute"] if row["year"] == 2023)
|
||||
assert row_2023["values"]["CN"] == 31
|
||||
assert row_2023["values"]["US"] == 41
|
||||
assert row_2023["values"]["EUROPE"] is None
|
||||
assert row_2023["values"]["APAC"] is None
|
||||
assert row_2023["values"]["OTHER"] is None
|
||||
assert row_2023["coverage"]["EUROPE"]["status"] == "incomplete"
|
||||
assert "DE" in row_2023["coverage"]["EUROPE"]["missing_members"]
|
||||
assert data["default_participants"] == ["CN", "US", "EUROPE", "APAC", "OTHER"]
|
||||
|
||||
|
||||
def test_anonymous_records_never_enter_the_location_repair_queue():
|
||||
from app.api.v1.visualization import convert_compute_centers_to_geojson
|
||||
from app.models.collected_data import CollectedData
|
||||
|
||||
record = CollectedData(
|
||||
source="epoch_ai_gpu",
|
||||
source_id="anonymous",
|
||||
name="Anonymous",
|
||||
extra_data={"compute_contract": "v1", "anonymous": True},
|
||||
)
|
||||
result = convert_compute_centers_to_geojson([record])
|
||||
assert result["features"] == []
|
||||
assert result["unresolved"] == []
|
||||
assert result["withheld_count"] == 1
|
||||
|
||||
|
||||
def test_absolute_report_year_mapping_and_bilateral_denominator_ignore_other_countries():
|
||||
absolute = compute_history(["CN"], "absolute")
|
||||
observed = {row["year"]: row for row in absolute["compute"]}
|
||||
assert observed[2022]["values"]["CN"] == 302
|
||||
assert observed[2022]["evidence_id"] == "caict-2023"
|
||||
assert observed[2023]["evidence_id"] == "caict-2024"
|
||||
bilateral = compute_history(["CN", "US", "JP"], "bilateral_share")
|
||||
values = next(row["values"] for row in bilateral["compute"] if row["year"] == 2023)
|
||||
assert values == {"CN": 43.06, "US": 56.94, "JP": None}
|
||||
for report in absolute["evidence"].values():
|
||||
if report.get("report_year"):
|
||||
assert report["url"].startswith("https://www.caict.ac.cn/")
|
||||
@@ -0,0 +1,18 @@
|
||||
from app.services.compute_center_verified_sites import get_verified_compute_site
|
||||
|
||||
|
||||
def test_registry_requires_exact_facility_identity_not_operator_name():
|
||||
assert get_verified_compute_site("epoch_ai_gpu", "NVIDIA") is None
|
||||
assert get_verified_compute_site("top500", "epoch_argonne_nl_sophia__formerly_theta_") is None
|
||||
|
||||
|
||||
def test_official_campus_anchors_preserve_evidence_and_site_level_precision():
|
||||
site = get_verified_compute_site("epoch_ai_gpu", "epoch_jamstec_zettascaler_2_2_gyoukou")
|
||||
assert site["city"] == "Yokohama"
|
||||
assert site["precision"] == "site"
|
||||
assert site["coordinate_basis"] == "official_access_map_center"
|
||||
assert site["sources"]
|
||||
site["latitude"] = 0
|
||||
assert get_verified_compute_site(
|
||||
"epoch_ai_gpu", "epoch_jamstec_zettascaler_2_2_gyoukou"
|
||||
)["latitude"] != 0
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -8,6 +9,10 @@ from app.services import earth_boundaries
|
||||
|
||||
|
||||
def write_geojson(path, name="Test"):
|
||||
names = [name]
|
||||
if name == "earth_admin0_boundaries":
|
||||
names = ["China", "India", "Japan", "Palestine", "Taiwan", "Hong Kong", "Macao", "Serbia", "Kosovo"]
|
||||
codes = {"China": "CHN", "India": "IND", "Japan": "JPN", "Palestine": "PSE", "Taiwan": "TWN", "Hong Kong": "HKG", "Macao": "MAC", "Serbia": "SRB", "Kosovo": "KOS"}
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
@@ -15,12 +20,17 @@ def write_geojson(path, name="Test"):
|
||||
"features": [
|
||||
{
|
||||
"type": "Feature",
|
||||
"properties": {"name": name},
|
||||
"properties": {
|
||||
"NAME": f"source renamed {item}" if item in {"Taiwan", "Kosovo"} else item,
|
||||
"ISO_A3": "-99" if item == "Kosovo" else codes.get(item, "TEST"),
|
||||
"ADM0_A3": "XKS" if item == "Kosovo" else codes.get(item, "TEST"),
|
||||
},
|
||||
"geometry": {
|
||||
"type": "Polygon",
|
||||
"coordinates": [[[-1, -1], [1, -1], [1, 1], [-1, 1], [-1, -1]]],
|
||||
},
|
||||
}
|
||||
for item in names
|
||||
],
|
||||
}
|
||||
),
|
||||
@@ -37,9 +47,14 @@ def patch_paths(monkeypatch, tmp_path):
|
||||
config = repo / "config/earth-boundary-sources.local.json"
|
||||
example = repo / "config/earth-boundary-sources.example.json"
|
||||
policy = repo / "config/earth-boundary-pov-policy.china-v1.json"
|
||||
geometry = repo / "resources/earth/boundary-pov-geometry.china-v1.json"
|
||||
for path in (source_dir, boundary_dir, pmtiles.parent, legacy.parent, config.parent):
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
policy.write_text('{"productionTileFormat":"pmtiles+mvt"}\n', encoding="utf-8")
|
||||
source_policy = Path(__file__).resolve().parents[2] / "config/earth-boundary-pov-policy.china-v1.json"
|
||||
policy.write_text(source_policy.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
geometry.parent.mkdir(parents=True, exist_ok=True)
|
||||
source_geometry = Path(__file__).resolve().parents[2] / "resources/earth/boundary-pov-geometry.china-v1.json"
|
||||
geometry.write_bytes(source_geometry.read_bytes())
|
||||
example.write_text('{"collectorConfigs":{}}\n', encoding="utf-8")
|
||||
monkeypatch.setattr(earth_boundaries, "REPO_ROOT", repo)
|
||||
monkeypatch.setattr(earth_boundaries, "SOURCE_OUTPUT_DIR", source_dir)
|
||||
@@ -49,10 +64,11 @@ def patch_paths(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(earth_boundaries, "BOUNDARY_OUTPUT_DIR", boundary_dir)
|
||||
monkeypatch.setattr(earth_boundaries, "BOUNDARY_MANIFEST_PATH", boundary_dir / "manifest.json")
|
||||
monkeypatch.setattr(earth_boundaries, "PMTILES_ARTIFACT_PATH", pmtiles)
|
||||
monkeypatch.setattr(earth_boundaries, "LEGACY_GEOJSON_PATH", legacy)
|
||||
monkeypatch.setattr(earth_boundaries, "POLICY_FALLBACK_PATH", legacy)
|
||||
monkeypatch.setattr(earth_boundaries, "LOCAL_CONFIG_PATH", config)
|
||||
monkeypatch.setattr(earth_boundaries, "EXAMPLE_CONFIG_PATH", example)
|
||||
monkeypatch.setattr(earth_boundaries, "POV_POLICY_PATH", policy)
|
||||
monkeypatch.setattr(earth_boundaries, "POV_GEOMETRY_PATH", geometry)
|
||||
return {
|
||||
"repo": repo,
|
||||
"config": config,
|
||||
@@ -62,27 +78,73 @@ def patch_paths(monkeypatch, tmp_path):
|
||||
}
|
||||
|
||||
|
||||
def write_fallback(path, policy_path, geometry_path):
|
||||
policy = earth_boundaries._read_json(policy_path)
|
||||
geometry = earth_boundaries._read_json(geometry_path)
|
||||
coverage = {
|
||||
"profile": "china-pov-v1",
|
||||
"sha256": earth_boundaries._stable_json_hash(policy),
|
||||
"geometrySha256": earth_boundaries._stable_json_hash(geometry),
|
||||
"reviewedGeometrySourceCommit": geometry["sourceCommit"],
|
||||
"applied": True,
|
||||
"appliedRuleIds": ["china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"],
|
||||
}
|
||||
path.write_text(json.dumps({"type": "FeatureCollection", "features": [], "povPolicy": coverage}), encoding="utf-8")
|
||||
|
||||
|
||||
def test_boundary_status_uses_legacy_provider_when_pmtiles_missing(monkeypatch, tmp_path):
|
||||
paths = patch_paths(monkeypatch, tmp_path)
|
||||
write_fallback(paths["legacy"], earth_boundaries.POV_POLICY_PATH, earth_boundaries.POV_GEOMETRY_PATH)
|
||||
|
||||
status = earth_boundaries.get_boundary_status()
|
||||
|
||||
assert status["provider"] == "policy-geojson-fallback"
|
||||
assert status["fallback_available"] is True
|
||||
assert status["high_precision_ready"] is False
|
||||
|
||||
|
||||
def test_boundary_status_rejects_unverified_fallback(monkeypatch, tmp_path):
|
||||
paths = patch_paths(monkeypatch, tmp_path)
|
||||
write_geojson(paths["legacy"])
|
||||
|
||||
status = earth_boundaries.get_boundary_status()
|
||||
|
||||
assert status["provider"] == "legacy-geojson"
|
||||
assert status["fallback_available"] is True
|
||||
assert status["high_precision_ready"] is False
|
||||
assert status["provider"] == "missing"
|
||||
assert status["fallback_available"] is False
|
||||
|
||||
|
||||
def test_boundary_status_prefers_high_precision_when_manifest_and_pmtiles_exist(monkeypatch, tmp_path):
|
||||
paths = patch_paths(monkeypatch, tmp_path)
|
||||
write_geojson(paths["legacy"])
|
||||
write_fallback(paths["legacy"], earth_boundaries.POV_POLICY_PATH, earth_boundaries.POV_GEOMETRY_PATH)
|
||||
paths["pmtiles"].write_bytes(b"pmtiles")
|
||||
paths["manifest"].write_text('{"tileProvider":"pmtiles-mvt"}\n', encoding="utf-8")
|
||||
(paths["manifest"].parent / "hover-index.geojson").write_text("{}", encoding="utf-8")
|
||||
coverage = {
|
||||
"profile": "china-pov-v1",
|
||||
"sha256": earth_boundaries._stable_json_hash(earth_boundaries._read_json(earth_boundaries.POV_POLICY_PATH)),
|
||||
"applied": True,
|
||||
"appliedRuleIds": ["china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"],
|
||||
"reviewedGeometrySourceCommit": earth_boundaries._read_json(earth_boundaries.POV_GEOMETRY_PATH)["sourceCommit"],
|
||||
"geometrySha256": earth_boundaries._stable_json_hash(earth_boundaries._read_json(earth_boundaries.POV_GEOMETRY_PATH)),
|
||||
}
|
||||
paths["manifest"].write_text(json.dumps({"tileProvider": "pmtiles-mvt", "hoverIndex": "hover-index.geojson", "povPolicy": coverage}), encoding="utf-8")
|
||||
|
||||
status = earth_boundaries.get_boundary_status()
|
||||
|
||||
assert status["provider"] == "pmtiles-mvt"
|
||||
assert status["high_precision_ready"] is True
|
||||
assert status["policy_publishable"] is False
|
||||
|
||||
|
||||
def test_boundary_status_rejects_unverified_high_precision(monkeypatch, tmp_path):
|
||||
paths = patch_paths(monkeypatch, tmp_path)
|
||||
write_fallback(paths["legacy"], earth_boundaries.POV_POLICY_PATH, earth_boundaries.POV_GEOMETRY_PATH)
|
||||
paths["pmtiles"].write_bytes(b"pmtiles")
|
||||
paths["manifest"].write_text('{"tileProvider":"pmtiles-mvt","povPolicy":{"applied":false}}', encoding="utf-8")
|
||||
|
||||
status = earth_boundaries.get_boundary_status()
|
||||
|
||||
assert status["provider"] == "policy-geojson-fallback"
|
||||
assert status["high_precision_ready"] is False
|
||||
|
||||
|
||||
def test_save_boundary_config_writes_local_config(monkeypatch, tmp_path):
|
||||
@@ -130,6 +192,22 @@ async def test_build_reports_missing_tools_after_source_artifacts(monkeypatch, t
|
||||
assert status["high_precision_ready"] is True
|
||||
assert (paths["repo"] / "data/earth-boundary-sources/manifest.json").exists()
|
||||
assert paths["manifest"].exists()
|
||||
manifest = json.loads(paths["manifest"].read_text(encoding="utf-8"))
|
||||
assert manifest["povPolicy"]["applied"] is True
|
||||
assert manifest["povPolicy"]["coverage"] == "partial"
|
||||
assert manifest["povPolicy"]["publicationReady"] is False
|
||||
assert "china-south-china-sea-islands" in manifest["povPolicy"]["unresolvedRuleIds"]
|
||||
hover = json.loads((paths["manifest"].parent / manifest["hoverIndex"]).read_text(encoding="utf-8"))
|
||||
by_rule = {
|
||||
feature["properties"].get("PLANET_POLICY_RULE"): feature
|
||||
for feature in hover["features"]
|
||||
}
|
||||
assert by_rule["china-hong-kong"]["properties"]["ISO_A3"] == "CHN"
|
||||
assert by_rule["china-macao"]["properties"]["ISO_A3"] == "CHN"
|
||||
assert all(
|
||||
feature["properties"].get("ADM0_A3") not in {"TWN", "KOS", "XKS"}
|
||||
for feature in hover["features"]
|
||||
)
|
||||
assert any(phase == "download" for _progress, phase, _message in progress_events)
|
||||
|
||||
|
||||
@@ -175,3 +253,23 @@ def test_earth_boundary_collectors_are_not_registered_as_datasources():
|
||||
assert removed.isdisjoint(DEFAULT_DATASOURCES)
|
||||
for source in removed:
|
||||
assert collector_registry.get(source) is None
|
||||
|
||||
|
||||
def test_static_policy_fallback_contains_reviewed_jeju_polygon():
|
||||
repo = Path(__file__).resolve().parents[2]
|
||||
path = repo / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson"
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
matches = [
|
||||
feature for feature in payload["features"]
|
||||
if feature["properties"].get("PLANET_GEOMETRY_SUPPLEMENT") == "jeju-island"
|
||||
]
|
||||
|
||||
assert len(matches) == 1
|
||||
jeju = matches[0]
|
||||
assert jeju["properties"]["ISO_A3"] == "KOR"
|
||||
assert jeju["properties"]["PLANET_SOURCE_NE_ID"] == 1159320985
|
||||
assert payload["povPolicy"]["geometrySupplement"]["jejuComponent"] == 3
|
||||
ring = jeju["geometry"]["coordinates"][0]
|
||||
assert len(ring) == 61
|
||||
assert min(point[0] for point in ring) < 126.53 < max(point[0] for point in ring)
|
||||
assert min(point[1] for point in ring) < 33.36 < max(point[1] for point in ring)
|
||||
@@ -0,0 +1,41 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.earth_geography_policy import display_country, display_iso_a3
|
||||
|
||||
|
||||
def test_missing_deployment_policy_has_an_actionable_error(monkeypatch, tmp_path):
|
||||
from app.core import earth_geography_policy as policy
|
||||
|
||||
policy._policy_country_by_code.cache_clear()
|
||||
monkeypatch.setattr(policy, "_POLICY_PATH", tmp_path / "missing-policy.json")
|
||||
try:
|
||||
with pytest.raises(FileNotFoundError, match="EARTH_DISPLAY_POLICY_MISSING"):
|
||||
policy.display_country("China")
|
||||
finally:
|
||||
policy._policy_country_by_code.cache_clear()
|
||||
|
||||
|
||||
def test_display_country_groups_china_regions_and_kosovo() -> None:
|
||||
for source in ("Taiwan", "TWN", "Hong Kong", "HKG", "Macao", "MAC", "中国(台湾)"):
|
||||
assert display_country(source) == "中国"
|
||||
assert display_iso_a3(source) == "CHN"
|
||||
for source in ("Kosovo", "XK", "SRB"):
|
||||
assert display_country(source) == "塞尔维亚"
|
||||
assert display_iso_a3(source) == "SRB"
|
||||
|
||||
|
||||
def test_display_country_keeps_other_country_and_rejects_unknown() -> None:
|
||||
assert display_country("Japan") == "日本"
|
||||
assert display_iso_a3("Japan") == "JPN"
|
||||
assert display_country("unexpected non-country") is None
|
||||
|
||||
|
||||
def test_country_projection_agrees_with_versioned_boundary_rules() -> None:
|
||||
path = Path(__file__).resolve().parents[2] / "config/earth-boundary-pov-policy.china-v1.json"
|
||||
policy = json.loads(path.read_text(encoding="utf-8"))
|
||||
for rule in policy["rules"]:
|
||||
for code in rule.get("sourceIsoA3", []):
|
||||
assert display_iso_a3(code) == rule.get("targetIsoA3", rule.get("parentIsoA3"))
|
||||
@@ -0,0 +1,37 @@
|
||||
from app.services.tv_streams import (
|
||||
CCTV4_HOMEPAGE,
|
||||
CCTV4_STREAM,
|
||||
UNSUPPORTED_CCTV4_STREAM,
|
||||
normalize_tv_settings,
|
||||
normalize_tv_source,
|
||||
)
|
||||
|
||||
|
||||
def test_default_keeps_aljazeera_and_does_not_offer_cdrm_as_plain_hls():
|
||||
settings = normalize_tv_settings(None)
|
||||
assert settings["default_source_id"] == "aljazeera-mubasher"
|
||||
cctv = next(source for source in settings["sources"] if source["id"] == "cctv4")
|
||||
assert cctv["source_type"] == "hls"
|
||||
assert cctv["stream_url"] == CCTV4_STREAM
|
||||
assert "美洲版" in cctv["name"]
|
||||
assert cctv["use_proxy"] is False
|
||||
assert cctv["homepage_url"] == CCTV4_HOMEPAGE
|
||||
|
||||
|
||||
def test_saved_legacy_default_is_corrected_without_mutating_input():
|
||||
saved = {"id": "cctv4", "source_type": "hls", "stream_url": UNSUPPORTED_CCTV4_STREAM}
|
||||
source = normalize_tv_source(saved)
|
||||
assert source["source_type"] == "hls"
|
||||
assert source["stream_url"] == CCTV4_STREAM
|
||||
assert source["use_proxy"] is False
|
||||
assert saved["stream_url"] == UNSUPPORTED_CCTV4_STREAM
|
||||
|
||||
|
||||
def test_custom_cctv_stream_and_fallback_preference_are_preserved():
|
||||
custom = {"id": "cctv4", "source_type": "hls", "stream_url": "https://example.com/licensed.m3u8"}
|
||||
settings = normalize_tv_settings({"auto_fallback": False, "sources": [custom]})
|
||||
source = next(source for source in settings["sources"] if source["id"] == "cctv4")
|
||||
assert source["stream_url"] == custom["stream_url"]
|
||||
assert source["source_type"] == "hls"
|
||||
assert source["use_proxy"] is True
|
||||
assert settings["auto_fallback"] is False
|
||||
@@ -76,6 +76,7 @@ def test_convert_compute_centers_to_geojson_unifies_sources():
|
||||
longitude=-90.05,
|
||||
metadata={
|
||||
"organization": "xAI",
|
||||
"location": "3231 Riverport Rd, Memphis, TN 38109",
|
||||
"gpu_type": "H100",
|
||||
"gpu_count": 100000,
|
||||
"value": "20000",
|
||||
@@ -168,6 +169,241 @@ def test_compute_center_source_coordinates_win_over_stored_location():
|
||||
compute_center_locations.set_compute_center_location_cache({})
|
||||
|
||||
|
||||
def test_epoch_country_level_coordinates_are_unresolved():
|
||||
record = _build_record(
|
||||
record_id=33,
|
||||
source="epoch_ai_gpu",
|
||||
data_type="gpu_cluster",
|
||||
name="Meta 100k",
|
||||
country="United States",
|
||||
city="",
|
||||
latitude=39.381266,
|
||||
longitude=-97.922211,
|
||||
metadata={
|
||||
"location": "United States of America",
|
||||
"raw_country": "United States of America",
|
||||
},
|
||||
)
|
||||
|
||||
payload = convert_compute_centers_to_geojson([record])
|
||||
|
||||
assert payload["features"] == []
|
||||
assert len(payload["unresolved"]) == 1
|
||||
assert payload["unresolved"][0]["source_id"] == "epoch_ai_gpu-33"
|
||||
assert "source_coordinates:country" in payload["unresolved"][0]["attempted_queries"]
|
||||
|
||||
|
||||
def test_epoch_city_coordinates_are_not_labeled_precise():
|
||||
record = _build_record(
|
||||
record_id=34,
|
||||
source="epoch_ai_gpu",
|
||||
data_type="gpu_cluster",
|
||||
name="Seoul Cluster",
|
||||
country="South Korea",
|
||||
city="",
|
||||
latitude=37.5665,
|
||||
longitude=126.978,
|
||||
metadata={"location": "Seoul", "raw_country": "South Korea"},
|
||||
)
|
||||
|
||||
result = compute_center_locations.resolve_compute_center_location_full(
|
||||
record, record.extra_data
|
||||
)
|
||||
|
||||
assert result.is_resolved
|
||||
assert result.location.location_precision == "city"
|
||||
assert result.location.needs_confirmation is True
|
||||
assert result.location.is_estimated is True
|
||||
assert result.location.city is None
|
||||
assert result.location.matched_location_name == "Seoul"
|
||||
assert "Epoch Location: Seoul" in result.location.location_source_note
|
||||
|
||||
|
||||
def test_epoch_city_geojson_preserves_source_location_without_guessing_city():
|
||||
record = _build_record(
|
||||
record_id=37,
|
||||
source="epoch_ai_gpu",
|
||||
data_type="gpu_cluster",
|
||||
name="Petrobras Fênix",
|
||||
country="Brazil",
|
||||
city="",
|
||||
latitude=-22.909534,
|
||||
longitude=-43.209934,
|
||||
metadata={
|
||||
"location": "Rio de Janeiro, Brazil",
|
||||
"raw_country": "Brazil",
|
||||
},
|
||||
)
|
||||
|
||||
payload = convert_compute_centers_to_geojson([record])
|
||||
|
||||
feature = payload["features"][0]
|
||||
assert feature["properties"]["location_precision"] == "city"
|
||||
assert feature["properties"]["matched_location_name"] == "Rio de Janeiro, Brazil"
|
||||
assert "Epoch Location: Rio de Janeiro, Brazil" in feature["properties"][
|
||||
"location_source_note"
|
||||
]
|
||||
|
||||
|
||||
def test_confirmed_stored_location_beats_epoch_precise_coordinates():
|
||||
compute_center_locations.set_compute_center_location_cache({
|
||||
"epoch_ai_gpu:epoch_ai_gpu-35": {
|
||||
"source": "epoch_ai_gpu",
|
||||
"source_id": "epoch_ai_gpu-35",
|
||||
"name": "Confirmed Site",
|
||||
"latitude": 35.0,
|
||||
"longitude": 139.0,
|
||||
"precision": "site",
|
||||
"confidence": 1.0,
|
||||
"location_source": "official_facility_registry",
|
||||
"needs_confirmation": False,
|
||||
}
|
||||
})
|
||||
try:
|
||||
record = _build_record(
|
||||
record_id=35,
|
||||
source="epoch_ai_gpu",
|
||||
data_type="gpu_cluster",
|
||||
name="Japan Cluster",
|
||||
country="Japan",
|
||||
city="Tokyo",
|
||||
latitude=35.68882,
|
||||
longitude=139.692526,
|
||||
metadata={
|
||||
"location": "1-1 Verified Street, Tokyo 100-0001, Japan",
|
||||
"raw_country": "Japan",
|
||||
},
|
||||
)
|
||||
|
||||
result = compute_center_locations.resolve_compute_center_location_full(
|
||||
record, record.extra_data
|
||||
)
|
||||
|
||||
assert result.location.location_source == "stored_compute_center_location"
|
||||
assert result.location.location_precision == "site"
|
||||
assert (result.location.latitude, result.location.longitude) == (35.0, 139.0)
|
||||
finally:
|
||||
compute_center_locations.set_compute_center_location_cache({})
|
||||
|
||||
|
||||
def test_legacy_seeded_country_coordinate_is_ignored_on_read():
|
||||
compute_center_locations.set_compute_center_location_cache({
|
||||
"epoch_ai_gpu:epoch_ai_gpu-36": {
|
||||
"source": "epoch_ai_gpu",
|
||||
"source_id": "epoch_ai_gpu-36",
|
||||
"name": "Legacy Country Point",
|
||||
"latitude": 36.386493,
|
||||
"longitude": 138.59223,
|
||||
"precision": "precise",
|
||||
"confidence": 1.0,
|
||||
"location_source": "source_coordinates",
|
||||
"needs_confirmation": False,
|
||||
}
|
||||
})
|
||||
try:
|
||||
record = _build_record(
|
||||
record_id=36,
|
||||
source="epoch_ai_gpu",
|
||||
data_type="gpu_cluster",
|
||||
name="Legacy Japan Cluster",
|
||||
country="Japan",
|
||||
city="",
|
||||
latitude=36.386493,
|
||||
longitude=138.59223,
|
||||
metadata={"location": "Japan", "raw_country": "Japan"},
|
||||
)
|
||||
|
||||
result = compute_center_locations.resolve_compute_center_location_full(
|
||||
record, record.extra_data
|
||||
)
|
||||
|
||||
assert result.location is None
|
||||
finally:
|
||||
compute_center_locations.set_compute_center_location_cache({})
|
||||
|
||||
|
||||
def test_verified_sites_replace_epoch_country_center_coordinates():
|
||||
specifications = [
|
||||
(
|
||||
"epoch_jamstec_zettascaler_2_0_gyoukou",
|
||||
"Gyoukou 2.0",
|
||||
"Japan",
|
||||
36.386493,
|
||||
138.59223,
|
||||
[139.625008, 35.380924],
|
||||
),
|
||||
(
|
||||
"epoch_jamstec_zettascaler_2_2_gyoukou",
|
||||
"Gyoukou 2.2",
|
||||
"Japan",
|
||||
36.386493,
|
||||
138.59223,
|
||||
[139.625008, 35.380924],
|
||||
),
|
||||
(
|
||||
"epoch_argonne_nl_sophia__formerly_theta_",
|
||||
"Sophia",
|
||||
"United States of America",
|
||||
39.381266,
|
||||
-97.922211,
|
||||
[-87.984498648496, 41.718109383287235],
|
||||
),
|
||||
]
|
||||
records = []
|
||||
for index, (source_id, name, country, latitude, longitude, _expected) in enumerate(
|
||||
specifications, start=40
|
||||
):
|
||||
record = _build_record(
|
||||
record_id=index,
|
||||
source="epoch_ai_gpu",
|
||||
data_type="gpu_cluster",
|
||||
name=name,
|
||||
country=country,
|
||||
city="",
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
metadata={"location": country, "raw_country": country},
|
||||
)
|
||||
record.source_id = source_id
|
||||
records.append(record)
|
||||
|
||||
payload = convert_compute_centers_to_geojson(records)
|
||||
|
||||
assert payload["unresolved"] == []
|
||||
assert len(payload["features"]) == 3
|
||||
for feature, specification in zip(payload["features"], specifications):
|
||||
assert feature["geometry"]["coordinates"] == specification[-1]
|
||||
assert feature["properties"]["location_precision"] == "site"
|
||||
assert feature["properties"]["location_source"] == "official_facility_registry"
|
||||
assert "https://" in feature["properties"]["location_source_note"]
|
||||
|
||||
|
||||
def test_verified_site_beats_epoch_city_level_source_coordinates():
|
||||
record = _build_record(
|
||||
record_id=44,
|
||||
source="epoch_ai_gpu",
|
||||
data_type="gpu_cluster",
|
||||
name="Gyoukou 2.2",
|
||||
country="Japan",
|
||||
city="Tokyo",
|
||||
latitude=35.68882,
|
||||
longitude=139.692526,
|
||||
metadata={"location": "Tokyo, Japan", "raw_country": "Japan"},
|
||||
)
|
||||
record.source_id = "epoch_jamstec_zettascaler_2_2_gyoukou"
|
||||
|
||||
result = compute_center_locations.resolve_compute_center_location_full(
|
||||
record, record.extra_data
|
||||
)
|
||||
|
||||
assert result.location.location_source == "official_facility_registry"
|
||||
assert result.location.location_precision == "site"
|
||||
assert (result.location.latitude, result.location.longitude) == (
|
||||
35.380924,
|
||||
139.625008,
|
||||
)
|
||||
|
||||
|
||||
def test_compute_center_geojson_uses_stored_location_when_source_coords_missing():
|
||||
compute_center_locations.set_compute_center_location_cache({
|
||||
"epoch_ai_gpu:epoch_ai_gpu-32": {
|
||||
@@ -637,7 +873,11 @@ async def test_compute_centers_geojson_endpoint_returns_stats():
|
||||
city="Memphis",
|
||||
latitude=35.15,
|
||||
longitude=-90.05,
|
||||
metadata={"value": "20000", "unit": "TFlop/s"},
|
||||
metadata={
|
||||
"location": "3231 Riverport Rd, Memphis, TN 38109",
|
||||
"value": "20000",
|
||||
"unit": "TFlop/s",
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
@@ -741,7 +981,11 @@ async def test_visualization_geo_summary_returns_counts(monkeypatch):
|
||||
city="Memphis",
|
||||
latitude=35.15,
|
||||
longitude=-90.05,
|
||||
metadata={"value": "20000", "unit": "TFlop/s"},
|
||||
metadata={
|
||||
"location": "3231 Riverport Rd, Memphis, TN 38109",
|
||||
"value": "20000",
|
||||
"unit": "TFlop/s",
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
Reference in new issue
Block a user