forked from linkong/planet
83 lines
3.2 KiB
Python
83 lines
3.2 KiB
Python
"""Quality gates shared by the two compute sources."""
|
|
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.countries import normalize_country
|
|
from app.models.compute_center_location import ComputeCenterLocationRecord
|
|
from app.models.data_snapshot import DataSnapshot
|
|
from app.services.collectors.base import BaseCollector
|
|
|
|
|
|
class ComputeCollector(BaseCollector):
|
|
fail_on_empty = True
|
|
preserve_snapshot_on_failure = True
|
|
|
|
async def _create_snapshot(
|
|
self, db: AsyncSession, task_id: int, data: list[dict], started_at: datetime
|
|
) -> int:
|
|
previous_count = await db.scalar(
|
|
select(DataSnapshot.record_count)
|
|
.where(
|
|
DataSnapshot.source == self.name,
|
|
DataSnapshot.is_current.is_(True),
|
|
DataSnapshot.status == "success",
|
|
)
|
|
.order_by(DataSnapshot.id.desc())
|
|
.limit(1)
|
|
)
|
|
if previous_count and len(data) < previous_count * 0.6:
|
|
raise ValueError("Compute source lost over 40% of rows; previous snapshot retained")
|
|
return await super()._create_snapshot(db, task_id, data, started_at)
|
|
|
|
async def _save_data(self, db: AsyncSession, data: list[dict], **kwargs) -> int:
|
|
if self.name == "top500":
|
|
await self._copy_verified_locations(db, data)
|
|
return await super()._save_data(db, data, **kwargs)
|
|
|
|
async def _copy_verified_locations(self, db: AsyncSession, data: list[dict]) -> None:
|
|
"""Keep historical location keys; copy only unambiguous exact identities.
|
|
|
|
Never migrate by rank: the machine occupying rank 1 changes over time.
|
|
"""
|
|
names = [item["name"] for item in data]
|
|
locations = (
|
|
(
|
|
await db.execute(
|
|
select(ComputeCenterLocationRecord).where(
|
|
ComputeCenterLocationRecord.source == self.name,
|
|
ComputeCenterLocationRecord.name.in_(names),
|
|
)
|
|
)
|
|
)
|
|
.scalars()
|
|
.all()
|
|
)
|
|
existing = {location.source_id for location in locations}
|
|
for item in data:
|
|
if item["source_id"] in existing:
|
|
continue
|
|
country = normalize_country(item["country"])
|
|
if not country:
|
|
continue
|
|
matches = [
|
|
location
|
|
for location in locations
|
|
if location.name == item["name"]
|
|
and normalize_country(location.country) == country
|
|
and (not location.site or location.site == item.get("metadata", {}).get("site"))
|
|
and not location.source_id.startswith("top500_system_")
|
|
]
|
|
if len(matches) != 1:
|
|
continue
|
|
old = matches[0]
|
|
values = {
|
|
column.name: getattr(old, column.name)
|
|
for column in old.__table__.columns
|
|
if column.name not in {"id", "source_id", "created_at", "updated_at"}
|
|
}
|
|
db.add(ComputeCenterLocationRecord(**values, source_id=item["source_id"]))
|
|
existing.add(item["source_id"])
|