forked from linkong/planet
181 lines
7.2 KiB
Python
181 lines
7.2 KiB
Python
"""Phase 3.1 domain freshness, sanitization, blind-spot injection, and endpoint tests."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime, timedelta
|
|
from httpx import ASGITransport, AsyncClient
|
|
import pytest
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.session import Base, get_db
|
|
from app.main import app
|
|
from app.models.aircraft import AircraftCurrentState
|
|
from app.models.compute_configuration_revision import ComputeConfigurationRevision
|
|
from app.models.datasource import DataSource
|
|
from app.models.task import CollectionTask
|
|
from app.services.ai.tool_registry import query_global_situational_tool
|
|
from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS
|
|
from app.services.source_freshness import (
|
|
DOMAIN_SPEC_BY_KEY,
|
|
VALID_FRESHNESS_STATUSES,
|
|
classify_domain_freshness,
|
|
compute_domain_freshness,
|
|
)
|
|
|
|
|
|
class _AsyncSQLiteSession:
|
|
def __init__(self, session: Session):
|
|
self._session = session
|
|
|
|
def get_bind(self):
|
|
return self._session.get_bind()
|
|
|
|
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 commit(self) -> None:
|
|
self._session.commit()
|
|
|
|
|
|
def _create_sqlite_session() -> Session:
|
|
engine = create_engine("sqlite:///:memory:")
|
|
Base.metadata.create_all(bind=engine)
|
|
return Session(engine)
|
|
|
|
|
|
def test_classify_domain_freshness_covers_all_seven_statuses():
|
|
now = datetime(2026, 12, 6, 12, 0, tzinfo=UTC)
|
|
spec = DOMAIN_SPEC_BY_KEY["aircraft"] # 300s threshold
|
|
|
|
cases = {
|
|
"fresh": dict(last_success_at=now - timedelta(minutes=2), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False),
|
|
"stale": dict(last_success_at=now - timedelta(minutes=8), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False),
|
|
"very_stale": dict(last_success_at=now - timedelta(minutes=30), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False),
|
|
"degraded": dict(last_success_at=now - timedelta(minutes=1), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=True, all_failed_offline=False),
|
|
"offline": dict(last_success_at=now - timedelta(minutes=1), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=True, all_failed_offline=True),
|
|
"disabled": dict(last_success_at=now - timedelta(minutes=1), has_active_source=False, has_any_source=True, all_disabled=True, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False),
|
|
"not_configured": dict(last_success_at=None, has_active_source=False, has_any_source=True, all_disabled=False, has_unconfigured_only=True, has_recent_failure=False, all_failed_offline=False),
|
|
}
|
|
|
|
for expected_status, kwargs in cases.items():
|
|
res = classify_domain_freshness(spec, now=now, **kwargs)
|
|
assert res["status"] == expected_status
|
|
assert res["status"] in VALID_FRESHNESS_STATUSES
|
|
assert res["is_blind_spot"] is (expected_status != "fresh")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_freshness_endpoint_sanitizes_internal_errors_and_computes_blind_spots():
|
|
sync_session = _create_sqlite_session()
|
|
now = datetime.now(UTC)
|
|
|
|
sync_session.add(
|
|
DataSource(
|
|
id=39,
|
|
name="adsb.lol",
|
|
source="adsb_lol_aircraft",
|
|
module="L4",
|
|
priority="P1",
|
|
frequency_minutes=1,
|
|
collector_class="ADSBCollector",
|
|
is_active=True,
|
|
last_run_at=now - timedelta(minutes=1),
|
|
last_status="success",
|
|
)
|
|
)
|
|
sync_session.add(
|
|
AircraftCurrentState(
|
|
icao24="ae0001",
|
|
lat=25.0,
|
|
lon=121.5,
|
|
source="adsb_lol_aircraft",
|
|
observed_at=now - timedelta(minutes=1),
|
|
ingested_at=now,
|
|
)
|
|
)
|
|
sync_session.add(
|
|
DataSource(
|
|
id=27,
|
|
name="barentswatch",
|
|
source="barentswatch_vessels",
|
|
module="L4",
|
|
priority="P1",
|
|
frequency_minutes=1,
|
|
collector_class="VesselCollector",
|
|
is_active=True,
|
|
last_run_at=now - timedelta(hours=2),
|
|
last_status="failed",
|
|
)
|
|
)
|
|
secret_url = "https://internal-secret.corp/token=TOP_SECRET_12345"
|
|
sync_session.add(
|
|
CollectionTask(
|
|
datasource_id=27,
|
|
source="barentswatch_vessels",
|
|
task_type="collect",
|
|
status="failed",
|
|
error_message=f"Traceback: ConnectError while dialing {secret_url}",
|
|
created_at=now,
|
|
)
|
|
)
|
|
sync_session.add(
|
|
ComputeConfigurationRevision(
|
|
publish_id="rev-fresh-001",
|
|
action="publish",
|
|
content_fingerprint="abc123",
|
|
is_default_content=False,
|
|
config_payload={},
|
|
published_at=now,
|
|
)
|
|
)
|
|
sync_session.commit()
|
|
|
|
async_db = _AsyncSQLiteSession(sync_session)
|
|
|
|
async def _override_get_db():
|
|
yield async_db
|
|
|
|
app.dependency_overrides[get_db] = _override_get_db
|
|
try:
|
|
report = await compute_domain_freshness(async_db, now=now)
|
|
serialized = str(report)
|
|
assert "TOP_SECRET_12345" not in serialized
|
|
assert "internal-secret.corp" not in serialized
|
|
assert "Traceback" not in serialized
|
|
|
|
by_domain = {d["domain"]: d for d in report["domains"]}
|
|
assert by_domain["aircraft"]["status"] == "fresh"
|
|
assert by_domain["compute"]["status"] == "fresh"
|
|
assert by_domain["vessels"]["status"] in {"stale", "offline", "degraded"}
|
|
assert any(b["domain"] == "vessels" for b in report["blind_spots"])
|
|
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
resp = await client.get("/api/v1/system/freshness")
|
|
assert resp.status_code == 200
|
|
payload = resp.json()
|
|
assert payload["blind_spot_count"] >= 1
|
|
assert "TOP_SECRET_12345" not in resp.text
|
|
assert "Traceback" not in resp.text
|
|
finally:
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_global_situational_tool_injects_blind_spots_and_workflow_prompts_enforce_rule():
|
|
sync_session = _create_sqlite_session()
|
|
async_db = _AsyncSQLiteSession(sync_session)
|
|
result = await query_global_situational_tool(async_db)
|
|
assert "blind_spots" in result
|
|
assert "freshness" in result
|
|
assert isinstance(result["blind_spots"], list)
|
|
assert len(result["blind_spots"]) >= 1
|
|
|
|
wf_map = {w["workflow_id"]: w for w in BUILTIN_WORKFLOWS}
|
|
for wf_id in ("default.general", "wargame.infrastructure"):
|
|
llm_nodes = [n for n in wf_map[wf_id]["graph"]["nodes"] if n.get("node_type") == "llm_agent"]
|
|
assert llm_nodes
|
|
prompt = llm_nodes[0]["system_prompt"]
|
|
assert "blind_spots" in prompt
|
|
assert "无事件" in prompt
|