252 lines
8.9 KiB
Python
252 lines
8.9 KiB
Python
"""Tests for §3.9 H3 convergence, dependency impact gating, and proactive pipeline isolation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import asynccontextmanager
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import h3
|
|
import pytest
|
|
from sqlalchemy import create_engine, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.migrations import discover_migrations
|
|
from app.db.session import Base
|
|
from app.models.aircraft import AircraftCurrentState
|
|
from app.models.collected_data import CollectedData
|
|
from app.models.compute_center_location import ComputeCenterLocationRecord
|
|
from app.models.gps_jamming import GPSJammingCell
|
|
from app.models.maritime_advisory import CableAdvisory
|
|
from app.models.situational_assessment import StagePresentation
|
|
from app.services.ai.proactive_pipeline import process_fusion_incident
|
|
from app.services.fusion.convergence import contains_causal_assertion, run_convergence_cycle
|
|
from app.services.fusion.dependency_impact import evaluate_cable_dependency_impact
|
|
|
|
|
|
class _AsyncSQLiteSession:
|
|
def __init__(self, session: Session):
|
|
self._session = session
|
|
|
|
def get_bind(self):
|
|
return self._session.get_bind()
|
|
|
|
def add(self, instance) -> None:
|
|
self._session.add(instance)
|
|
|
|
def add_all(self, instances) -> None:
|
|
self._session.add_all(instances)
|
|
|
|
async def execute(self, statement, params=None):
|
|
return (
|
|
self._session.execute(statement, params)
|
|
if params is not None
|
|
else self._session.execute(statement)
|
|
)
|
|
|
|
async def flush(self) -> None:
|
|
self._session.flush()
|
|
|
|
async def commit(self) -> None:
|
|
self._session.commit()
|
|
|
|
|
|
class _AsyncConnShim:
|
|
def __init__(self, conn):
|
|
self._conn = conn
|
|
self.dialect = conn.dialect
|
|
|
|
async def execute(self, stmt, params=None):
|
|
return (
|
|
self._conn.execute(stmt, params)
|
|
if params is not None
|
|
else self._conn.execute(stmt)
|
|
)
|
|
|
|
|
|
async def _make_sqlite_session():
|
|
engine = create_engine("sqlite:///:memory:")
|
|
with engine.begin() as raw_conn:
|
|
shim = _AsyncConnShim(raw_conn)
|
|
for step in discover_migrations():
|
|
if step.version in {"0009", "0010", "0011"}:
|
|
await step.upgrade(shim)
|
|
Base.metadata.create_all(raw_conn, checkfirst=True)
|
|
|
|
@asynccontextmanager
|
|
async def _factory():
|
|
with Session(engine) as session:
|
|
yield _AsyncSQLiteSession(session)
|
|
|
|
return engine, _factory
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_convergence_requires_two_domains_and_avoids_causality() -> None:
|
|
_engine, session_factory = await _make_sqlite_session()
|
|
now = datetime(2026, 6, 15, 12, 0, tzinfo=UTC)
|
|
|
|
async with session_factory() as db:
|
|
sg_h3 = h3.latlng_to_cell(1.30, 103.85, 4)
|
|
# Single domain only -> should NOT generate candidate_correlation
|
|
db.add(
|
|
GPSJammingCell(
|
|
h3_index=sg_h3,
|
|
observed_date=now.date().isoformat(),
|
|
lat=1.30,
|
|
lon=103.85,
|
|
resolution=4,
|
|
level="high",
|
|
bad_ratio=0.55,
|
|
aircraft_count=12,
|
|
boundary=[[1.2, 103.7], [1.4, 103.9]],
|
|
source="gpsjam_interference",
|
|
ingested_at=now,
|
|
)
|
|
)
|
|
await db.commit()
|
|
res_single = await run_convergence_cycle(db, now=now)
|
|
assert res_single == []
|
|
|
|
# Add a second distinct domain (emergency aircraft) in the same coordinates
|
|
db.add(
|
|
AircraftCurrentState(
|
|
icao24="ae9991",
|
|
callsign="RCH123",
|
|
lat=1.30,
|
|
lon=103.85,
|
|
squawk="7700",
|
|
on_ground=False,
|
|
is_military=True,
|
|
is_emergency=True,
|
|
source="adsb_lol_aircraft",
|
|
observed_at=now - timedelta(minutes=15),
|
|
ingested_at=now,
|
|
)
|
|
)
|
|
await db.commit()
|
|
|
|
res_multi = await run_convergence_cycle(db, now=now)
|
|
assert len(res_multi) == 2 # 6h + 24h windows
|
|
for inc in res_multi:
|
|
assert inc.assessment_kind == "candidate_correlation"
|
|
assert "待核查关联" in inc.title
|
|
assert not contains_causal_assertion(inc.title)
|
|
assert not contains_causal_assertion(inc.signal_summary.get("co_occurrence_note", ""))
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dependency_impact_gates_on_independent_evidence_and_proactive_pipeline() -> None:
|
|
_engine, session_factory = await _make_sqlite_session()
|
|
now = datetime(2026, 6, 15, 12, 0, tzinfo=UTC)
|
|
|
|
async with session_factory() as db:
|
|
# Topology: apg-1 + backup sea-me-we-6 both land in city 901 (Singapore -> compute center 77)
|
|
db.add_all(
|
|
[
|
|
CollectedData(
|
|
source="arcgis_cables",
|
|
source_id="apg-1",
|
|
data_type="cable",
|
|
name="APG Cable",
|
|
extra_data={"cable_id": "apg-1", "coordinates": [[103.6, 1.25], [103.8, 1.3]]},
|
|
is_current=True,
|
|
collected_at=now,
|
|
),
|
|
CollectedData(
|
|
source="arcgis_cables",
|
|
source_id="smw6",
|
|
data_type="cable",
|
|
name="SEA-ME-WE 6",
|
|
extra_data={"cable_id": "smw6", "coordinates": [[103.5, 1.22], [103.9, 1.31]]},
|
|
is_current=True,
|
|
collected_at=now,
|
|
),
|
|
CollectedData(
|
|
source="arcgis_landing_points",
|
|
source_id="tuas",
|
|
data_type="landing_point",
|
|
name="Tuas",
|
|
extra_data={"city_id": 901, "country": "Singapore", "latitude": 1.32, "longitude": 103.64},
|
|
is_current=True,
|
|
collected_at=now,
|
|
),
|
|
CollectedData(
|
|
source="arcgis_cable_landing_relation",
|
|
source_id="r1",
|
|
data_type="relation",
|
|
name="apg-tuas",
|
|
extra_data={"cable_id": "apg-1", "city_id": 901},
|
|
is_current=True,
|
|
collected_at=now,
|
|
),
|
|
CollectedData(
|
|
source="arcgis_cable_landing_relation",
|
|
source_id="r2",
|
|
data_type="relation",
|
|
name="smw6-tuas",
|
|
extra_data={"cable_id": "smw6", "city_id": 901},
|
|
is_current=True,
|
|
collected_at=now,
|
|
),
|
|
ComputeCenterLocationRecord(
|
|
id=77,
|
|
source="top500",
|
|
source_id="sg-77",
|
|
name="SG National HPC",
|
|
country="SG",
|
|
latitude=1.34,
|
|
longitude=103.81,
|
|
verified_at=now,
|
|
),
|
|
]
|
|
)
|
|
await db.commit()
|
|
|
|
# Without independent NGA/operator/BGP evidence -> strictly None
|
|
no_ev = await evaluate_cable_dependency_impact(
|
|
db,
|
|
cable_id="apg-1",
|
|
suspect_object_ids=["vessel:412111222"],
|
|
now=now,
|
|
)
|
|
assert no_ev is None
|
|
|
|
# Add matching NGA CableAdvisory -> upgrades to dependency_impact with backup cables & arcs
|
|
db.add(
|
|
CableAdvisory(
|
|
source_warning_id="HYDROPAC 111/26",
|
|
text="APG SUBMARINE CABLE REPAIR OPERATIONS IN PROGRESS",
|
|
lat=1.28,
|
|
lon=103.72,
|
|
issued_at=now - timedelta(hours=1),
|
|
matched_cable_ids=["apg-1"],
|
|
match_method="haversine_50km",
|
|
ingested_at=now,
|
|
)
|
|
)
|
|
await db.commit()
|
|
|
|
impact_inc = await evaluate_cable_dependency_impact(
|
|
db,
|
|
cable_id="apg-1",
|
|
suspect_object_ids=["vessel:412111222"],
|
|
now=now,
|
|
)
|
|
assert impact_inc is not None
|
|
assert impact_inc.assessment_kind == "dependency_impact"
|
|
assert "SG" in impact_inc.signal_summary["impacted_countries"]
|
|
assert any(b["cable_id"] == "smw6" for b in impact_inc.signal_summary["backup_cables"])
|
|
assert len(impact_inc.signal_summary["impact_arcs"]) >= 1
|
|
|
|
pro_res = await process_fusion_incident(db, impact_inc)
|
|
assert pro_res["workflow_id"] == "wargame.cable_protection"
|
|
assert pro_res["published_presentation"] is not None
|
|
persisted = (
|
|
await db.execute(
|
|
select(StagePresentation).where(
|
|
StagePresentation.presentation_key == pro_res["presentation_key"]
|
|
)
|
|
)
|
|
).scalars().first()
|
|
assert persisted is not None
|