"""Comprehensive unit & integration tests for collection storage policy & snapshot controls.""" from __future__ import annotations from datetime import UTC, datetime, timedelta from pathlib import Path from unittest.mock import AsyncMock, patch import pytest from httpx import ASGITransport, AsyncClient from sqlalchemy import create_engine, func, select from sqlalchemy.orm import Session from app.api.v1.datasource_config import delete_config from app.core.security import get_current_user from app.db.session import ( PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL, PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS, PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL, Base, get_db, ) from app.main import app from app.models.bgp_anomaly import BGPAnomaly from app.models.bgp_incident import BGPIncident from app.models.bgp_observation import BGPObservation from app.models.collected_data import CollectedData from app.models.data_snapshot import DataSnapshot from app.models.datasource import DataSource from app.models.datasource_config import DataSourceConfig from app.models.datasource_mapping import DataSourceMappingTemplate from app.models.earth_news import EarthNewsItem from app.models.system_log import ObservabilityEvent, SystemLog from app.models.system_setting import SystemSetting from app.models.task import CollectionTask from app.models.user import User from app.models.vessel import ( AISRawObservation, AISSourceHealth, VesselCurrentState, VesselPosition, ) from app.services.collectors.base import BaseCollector from app.services.collectors.bgp_common import ( create_bgp_anomalies_for_batch, slim_bgp_events_for_collected_data, ) from app.services.collectors.downloads import ResumableFileDownloader from app.services.collectors.registry import collector_registry from app.services.collectors.telegeography import TeleGeographyCableCollector from app.services.storage_maintenance import run_storage_retention_maintenance from app.services.storage_policy import ( DEFAULT_STORAGE_POLICY, apply_global_snapshot_action, ensure_default_storage_policy, get_storage_policy, normalize_storage_policy, resolve_snapshot_mode, save_storage_policy, set_source_snapshot_mode, summarize_storage_policy, ) from app.services.vessel_ais_aggregation import ( get_aggregated_vessel, get_aggregated_vessel_track, get_aggregated_vessels, prune_expired_vessel_track_points, record_vessel_ais_observation, ) class _AsyncSQLiteSession: """AsyncSession-compatible test adapter over an isolated in-memory SQLite Session.""" 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 delete(self, instance) -> None: self._session.delete(instance) async def get(self, entity, ident): return self._session.get(entity, ident) async def execute(self, statement, params=None): if params is not None: return self._session.execute(statement, params) return self._session.execute(statement) async def scalar(self, statement): return self._session.scalar(statement) async def scalars(self, statement): return self._session.scalars(statement) async def flush(self) -> None: self._session.flush() async def commit(self) -> None: self._session.commit() async def rollback(self) -> None: self._session.rollback() async def refresh(self, instance) -> None: self._session.refresh(instance) @pytest.fixture def sqlite_db(): engine = create_engine("sqlite:///:memory:") Base.metadata.create_all( engine, tables=[ SystemSetting.__table__, DataSource.__table__, DataSourceConfig.__table__, DataSourceMappingTemplate.__table__, CollectionTask.__table__, DataSnapshot.__table__, CollectedData.__table__, AISRawObservation.__table__, AISSourceHealth.__table__, VesselCurrentState.__table__, VesselPosition.__table__, BGPObservation.__table__, BGPAnomaly.__table__, BGPIncident.__table__, EarthNewsItem.__table__, SystemLog.__table__, ObservabilityEvent.__table__, User.__table__, ], ) with Session(engine) as session: yield _AsyncSQLiteSession(session) engine.dispose() class _SampleCollector(BaseCollector): name = "sample_test_collector" priority = "P1" module = "L2" data_type = "sample_entity" def __init__(self, items=None, *, full_reconcile: bool = False): super().__init__() self._items = items or [] self._full_reconcile = full_reconcile async def fetch(self): if self._full_reconcile: self._mark_fetch_complete(True) return list(self._items) def test_storage_policy_defaults_sparse_overrides_and_tristate(): policy = normalize_storage_policy(None) assert policy["default_mode"] == "single" assert policy["overrides"] == {"top500": "annual", "epoch_ai_gpu": "annual"} assert policy["history_retention_days"] == 30 assert policy["bgp_observation_retention_days"] == 7 assert policy["bgp_single_batch_max_rows"] == 500 assert resolve_snapshot_mode(policy, "top500") == "annual" assert resolve_snapshot_mode(policy, "iptoasn_prefix_geo") == "single" # Annual is coerced to history for non-compute sources, and matching default drops override. updated = set_source_snapshot_mode(policy, "iptoasn_prefix_geo", "annual") assert updated["overrides"]["iptoasn_prefix_geo"] == "history" cleared = set_source_snapshot_mode(updated, "iptoasn_prefix_geo", "single") assert "iptoasn_prefix_geo" not in cleared["overrides"] sources = ["top500", "epoch_ai_gpu", "iptoasn_prefix_geo", "celestrak_tle"] summary_partial = summarize_storage_policy(policy, sources) assert summary_partial["master_state"] == "partial" assert summary_partial["snapshot_enabled_count"] == 2 assert summary_partial["annual_count"] == 2 assert summary_partial["single_count"] == 2 all_single = apply_global_snapshot_action(policy, "all_single") summary_off = summarize_storage_policy(all_single, sources) assert summary_off["master_state"] == "off" assert summary_off["snapshot_enabled_count"] == 0 all_history = apply_global_snapshot_action(policy, "all_history") summary_all = summarize_storage_policy(all_history, sources) assert summary_all["master_state"] == "all" assert summary_all["history_count"] == 4 restored = apply_global_snapshot_action(all_history, "recommended_default") assert restored["overrides"] == DEFAULT_STORAGE_POLICY["overrides"] @pytest.mark.asyncio async def test_ensure_default_storage_policy_protects_existing_db(sqlite_db): # Empty database initializes auto_prune_enabled=True with Option B defaults. fresh_policy = await ensure_default_storage_policy(sqlite_db) assert fresh_policy["default_mode"] == "single" assert fresh_policy["overrides"] == {"top500": "annual", "epoch_ai_gpu": "annual"} assert fresh_policy["auto_prune_enabled"] is True # Reset collection_storage and simulate an existing database with pre-existing snapshot + system retention=45. sqlite_db._session.query(SystemSetting).delete() sqlite_db.add(SystemSetting(category="system", payload={"data_retention_days": 45})) sqlite_db.add( DataSnapshot( datasource_id=1, source="top500", status="success", is_current=True, record_count=500, ) ) await sqlite_db.commit() upgraded_policy = await ensure_default_storage_policy(sqlite_db) assert upgraded_policy["auto_prune_enabled"] is False assert upgraded_policy["history_retention_days"] == 45 assert upgraded_policy["overrides"] == {"top500": "annual", "epoch_ai_gpu": "annual"} @pytest.mark.asyncio async def test_base_collector_single_mode_incremental_upsert_preserves_history(sqlite_db, monkeypatch): await save_storage_policy( sqlite_db, {"default_mode": "single", "overrides": {}}, sync_system_retention=False, ) monkeypatch.setattr(collector_registry, "is_active", lambda _name: True) # Seed pre-existing historical non-current row that must NEVER be touched or deleted in single mode. old_history = CollectedData( source="sample_test_collector", source_id="a", entity_key="sample_test_collector:a", data_type="sample_entity", name="Alpha Legacy", is_current=False, extra_data={}, ) sqlite_db.add(old_history) await sqlite_db.commit() # Run 1: create A and B. collector1 = _SampleCollector( [ {"source_id": "a", "name": "Alpha", "country": "China", "value": 10}, {"source_id": "b", "name": "Beta", "country": "United States", "value": 20}, ] ) res1 = await collector1.run(sqlite_db) assert res1["status"] == "success" assert collector1._last_save_summary == {"created": 2, "updated": 0, "unchanged": 0, "deleted": 0} snapshots_after_1 = list((await sqlite_db.scalars(select(DataSnapshot))).all()) assert len(snapshots_after_1) == 1 first_snapshot_id = snapshots_after_1[0].id assert snapshots_after_1[0].record_count == 2 current_rows_1 = list( ( await sqlite_db.scalars( select(CollectedData).where( CollectedData.source == "sample_test_collector", CollectedData.is_current.is_(True), ) ) ).all() ) assert len(current_rows_1) == 2 assert all(row.content_hash for row in current_rows_1) id_a_run1 = next(r.id for r in current_rows_1 if r.source_id == "a") # Run 2: identical payload -> reuses same DataSnapshot, 0 writes to unchanged rows. collector2 = _SampleCollector( [ {"source_id": "a", "name": "Alpha", "country": "China", "value": 10}, {"source_id": "b", "name": "Beta", "country": "United States", "value": 20}, ] ) res2 = await collector2.run(sqlite_db) assert res2["status"] == "success" assert collector2._last_save_summary == {"created": 0, "updated": 0, "unchanged": 2, "deleted": 0} snapshots_after_2 = list((await sqlite_db.scalars(select(DataSnapshot))).all()) assert len(snapshots_after_2) == 1 assert snapshots_after_2[0].id == first_snapshot_id # Run 3a: Partial response missing B -> preserves existing B cleanly without physical delete! collector_partial = _SampleCollector( [ {"source_id": "a", "name": "Alpha", "country": "China", "value": 99}, ], full_reconcile=False, ) res_partial = await collector_partial.run(sqlite_db) assert res_partial["status"] == "success" assert res_partial["records_processed"] == 2 assert collector_partial._last_save_summary == { "created": 0, "updated": 1, "unchanged": 0, "deleted": 0, } partial_current_keys = { r.source_id for r in ( await sqlite_db.scalars( select(CollectedData).where( CollectedData.source == "sample_test_collector", CollectedData.is_current.is_(True), ) ) ).all() } assert partial_current_keys == {"a", "b"} # Run 3b: Confirmed full-universe fetch removes vanished current B, adds C, preserves old_history. collector3 = _SampleCollector( [ {"source_id": "a", "name": "Alpha", "country": "China", "value": 99}, {"source_id": "c", "name": "Gamma", "country": "Japan", "value": 30}, ], full_reconcile=True, ) res3 = await collector3.run(sqlite_db) assert res3["status"] == "success" assert collector3._last_save_summary == {"created": 1, "updated": 0, "unchanged": 1, "deleted": 1} all_rows_3 = list((await sqlite_db.scalars(select(CollectedData))).all()) current_rows_3 = [r for r in all_rows_3 if r.is_current] historical_rows_3 = [r for r in all_rows_3 if not r.is_current] assert {r.source_id for r in current_rows_3} == {"a", "c"} updated_a = next(r for r in current_rows_3 if r.source_id == "a") assert updated_a.id == id_a_run1 assert updated_a.previous_record_id is None assert updated_a.extra_data["value"] == 99 # Old historical row untouched! assert len(historical_rows_3) == 1 assert historical_rows_3[0].name == "Alpha Legacy" # Run 4: failure while reusing current snapshot restores healthy snapshot metadata. collector_fail = _SampleCollector([{"source_id": "a", "name": "Alpha", "value": 1}]) monkeypatch.setattr( collector_fail, "_save_data", AsyncMock(side_effect=RuntimeError("simulated write error")), ) res_fail = await collector_fail.run(sqlite_db) assert res_fail["status"] == "failed" reloaded_snap = await sqlite_db.get(DataSnapshot, first_snapshot_id) assert reloaded_snap is not None assert reloaded_snap.status == "success" assert reloaded_snap.is_current is True assert reloaded_snap.record_count == 2 @pytest.mark.asyncio async def test_annual_mode_freezes_previous_year_milestone(sqlite_db, monkeypatch): class _ComputeLikeCollector(_SampleCollector): name = "top500" data_type = "supercomputer" await save_storage_policy( sqlite_db, {"default_mode": "single", "overrides": {"top500": "annual"}}, sync_system_retention=False, ) monkeypatch.setattr(collector_registry, "is_active", lambda _name: True) # Seed an active 2025 current snapshot and row. snap_2025 = DataSnapshot( datasource_id=1, source="top500", snapshot_key="top500:10", started_at=datetime(2025, 11, 15, tzinfo=UTC), completed_at=datetime(2025, 11, 15, tzinfo=UTC), record_count=1, status="success", is_current=True, summary={"created": 1, "storage_mode": "annual"}, ) sqlite_db.add(snap_2025) await sqlite_db.commit() sqlite_db.add( CollectedData( snapshot_id=snap_2025.id, source="top500", source_id="top500_1", entity_key="top500:top500_1", data_type="supercomputer", name="Machine 2025", collected_at=datetime(2025, 11, 15, tzinfo=UTC), is_current=True, extra_data={"rank": 1}, ) ) await sqlite_db.commit() # Rollover run in 2026 freezes 2025 snapshot with milestone_year=2025 and creates new 2026 current snapshot. collector = _ComputeLikeCollector( [{"source_id": "top500_1", "name": "Machine 2026", "country": "China", "value": 5e17}] ) result = await collector.run(sqlite_db) assert result["status"] == "success" snapshots = list( ( await sqlite_db.scalars( select(DataSnapshot).where(DataSnapshot.source == "top500").order_by(DataSnapshot.id.asc()) ) ).all() ) assert len(snapshots) == 2 assert snapshots[0].is_current is False assert snapshots[0].summary["milestone_year"] == 2025 assert snapshots[1].is_current is True assert snapshots[1].parent_snapshot_id == snapshots[0].id # Same-year follow-up run reuses the 2026 snapshot in-place instead of creating a 3rd snapshot. collector_again = _ComputeLikeCollector( [{"source_id": "top500_1", "name": "Machine 2026", "country": "China", "value": 5e17}] ) result_again = await collector_again.run(sqlite_db) assert result_again["status"] == "success" snapshots_after = list( (await sqlite_db.scalars(select(DataSnapshot).where(DataSnapshot.source == "top500"))).all() ) assert len(snapshots_after) == 2 @pytest.mark.asyncio async def test_file_sha256_short_circuit_skips_transform_and_save(sqlite_db, tmp_path, monkeypatch): await save_storage_policy( sqlite_db, {"default_mode": "single", "overrides": {}}, sync_system_retention=False, ) monkeypatch.setattr(collector_registry, "is_active", lambda _name: True) sample_file = Path(tmp_path) / "dataset.txt" sample_file.write_text("prefix-1\nprefix-2\n", encoding="utf-8") downloader = ResumableFileDownloader(cache_namespace="test", cache_root=tmp_path) digest = downloader.get_file_sha256("https://example.invalid/dataset.txt", ".txt", sample_file) assert digest snap = DataSnapshot( datasource_id=1, source="short_circuit_source", status="success", is_current=True, record_count=42, completed_at=datetime.now(UTC), summary={"file_sha256": digest, "storage_mode": "single"}, ) sqlite_db.add(snap) await sqlite_db.commit() sqlite_db.add( CollectedData( snapshot_id=snap.id, source="short_circuit_source", source_id="1", entity_key="short_circuit_source:1", data_type="prefix_geography", is_current=True, extra_data={}, ) ) await sqlite_db.commit() class _FileCollector(BaseCollector): name = "short_circuit_source" fail_on_empty = True transform_called = False async def fetch(self): matched = await self._can_short_circuit_unchanged_file( self._db_session, file_sha256=digest, ) if matched is not None: self._short_circuited_snapshot_id = matched.id return [] return [{"source_id": "1"}] def transform(self, raw_data): self.transform_called = True return raw_data collector = _FileCollector() res = await collector.run(sqlite_db) assert res["status"] == "success" assert res["unchanged_file_skip"] is True assert res["records_processed"] == 42 assert collector.transform_called is False @pytest.mark.asyncio async def test_ais_option_b_skips_raw_table_and_reads_current_state(sqlite_db): observed_t1 = datetime.now(UTC) - timedelta(minutes=15) observed_t2 = datetime.now(UTC) - timedelta(minutes=5) stale_t0 = datetime.now(UTC) - timedelta(hours=30) # Stale point outside 24h window should be pruned while keeping recent 24h track intact. await record_vessel_ais_observation( sqlite_db, source="aisstream_vessels", normalized_payload={ "mmsi": 413000123, "lat": 30.90, "lon": 121.10, "sog": 9.0, "cog": 170.0, "received_at": stale_t0, }, delivery_mode="realtime_stream", transport="websocket", message_type="PositionReport", observed_at=stale_t0, persist_raw=False, ) pos_1 = await record_vessel_ais_observation( sqlite_db, source="aisstream_vessels", normalized_payload={ "mmsi": 413000123, "lat": 31.10, "lon": 121.30, "sog": 10.5, "cog": 175.0, "received_at": observed_t1, }, delivery_mode="realtime_stream", transport="websocket", message_type="PositionReport", observed_at=observed_t1, persist_raw=False, ) assert isinstance(pos_1, VesselCurrentState) pos_2 = await record_vessel_ais_observation( sqlite_db, source="aisstream_vessels", normalized_payload={ "mmsi": 413000123, "lat": 31.23, "lon": 121.47, "sog": 11.2, "cog": 180.0, "received_at": observed_t2, }, delivery_mode="realtime_stream", transport="websocket", message_type="PositionReport", observed_at=observed_t2, persist_raw=False, ) assert isinstance(pos_2, VesselCurrentState) # Follow-up ShipStaticData without coordinates enriches existing VesselCurrentState cleanly. static_result = await record_vessel_ais_observation( sqlite_db, source="aisstream_vessels", normalized_payload={ "mmsi": 413000123, "name": "PACIFIC STAR", "vessel_type": 70, "vessel_type_name": "Cargo", "received_at": observed_t2 + timedelta(seconds=10), }, delivery_mode="realtime_stream", transport="websocket", message_type="ShipStaticData", observed_at=observed_t2 + timedelta(seconds=10), persist_raw=False, ) assert isinstance(static_result, VesselCurrentState) assert static_result.name == "PACIFIC STAR" await sqlite_db.commit() pruned_stale = await prune_expired_vessel_track_points(sqlite_db, force=True) assert pruned_stale == 1 await sqlite_db.commit() raw_count = await sqlite_db.scalar(select(func.count(AISRawObservation.id))) assert raw_count == 0 pos_count = await sqlite_db.scalar(select(func.count(VesselPosition.id))) assert pos_count == 2 vessels = await get_aggregated_vessels(sqlite_db) assert len(vessels) == 1 assert vessels[0]["mmsi"] == 413000123 assert vessels[0]["name"] == "PACIFIC STAR" detail = await get_aggregated_vessel(sqlite_db, 413000123) assert detail is not None assert detail["lat"] == pytest.approx(31.23) track = await get_aggregated_vessel_track( sqlite_db, 413000123, cutoff=datetime.now(UTC) - timedelta(hours=24), ) assert len(track) == 2 assert [(round(pt["lat"], 2), round(pt["lon"], 2)) for pt in track] == [ (31.10, 121.30), (31.23, 121.47), ] assert all(pt["selected_reason"] == "track_24h" for pt in track) async def override_get_db(): yield sqlite_db app.dependency_overrides[get_db] = override_get_db try: async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: resp = await client.get("/api/v1/visualization/vessels/413000123/track?hours=24") assert resp.status_code == 200 body = resp.json() assert body["count"] == 1 feature = body["features"][0] assert feature["properties"]["point_count"] == 2 assert feature["geometry"]["coordinates"] == [[121.3, 31.1], [121.47, 31.23]] finally: app.dependency_overrides.clear() @pytest.mark.asyncio async def test_bgp_slim_batch_and_observation_origin_baseline(sqlite_db): raw_events = [ { "source_id": f"evt-{idx}", "metadata": {"prefix": f"203.0.{idx}.0/24", "raw_message": {"huge": "payload"}}, } for idx in range(600) ] slimmed = slim_bgp_events_for_collected_data(raw_events, max_rows=500) assert len(slimmed) == 500 assert slimmed[0]["source_id"] == "evt-100" assert "raw_message" not in slimmed[0]["metadata"] # Seed prior BGPObservation sharing the SAME snapshot_id (reused in single mode) with a different task_id! sqlite_db.add( BGPObservation( snapshot_id=1, task_id=10, source="ris_live_bgp", prefix="198.51.100.0/24", event_type="announcement", origin_asn=64496, as_path=[3356, 64496], observed_at=datetime.now(UTC) - timedelta(hours=1), ) ) await sqlite_db.commit() with ( patch( "app.services.collectors.bgp_common.enrich_bgp_events_for_batch", new=AsyncMock(side_effect=lambda _db, *, source, events: events), ), patch( "app.services.collectors.bgp_common.create_bgp_incidents_for_anomalies", new=AsyncMock(return_value=1), ), ): anomalies = await create_bgp_anomalies_for_batch( sqlite_db, source="ris_live_bgp", snapshot_id=1, task_id=11, events=[ { "reference_date": datetime.now(UTC).isoformat(), "metadata": { "prefix": "198.51.100.0/24", "origin_asn": 64497, "collector": "rrc00", "collector_location": {"country": "NL", "city": "Amsterdam"}, "as_path": [3356, 64497], "event_type": "announcement", "timestamp": datetime.now(UTC).isoformat(), }, } ], ) assert anomalies == 1 @pytest.mark.asyncio async def test_storage_retention_maintenance_gates_and_preserves_milestones(sqlite_db): now = datetime(2026, 11, 20, tzinfo=UTC) expired_time = now - timedelta(days=45) old_bgp_time = now - timedelta(days=10) recent_time = now - timedelta(days=2) expired_snap = DataSnapshot( datasource_id=1, source="celestrak_tle", is_current=False, status="success", started_at=expired_time, completed_at=expired_time, summary={"storage_mode": "history"}, ) milestone_snap = DataSnapshot( datasource_id=1, source="top500", is_current=False, status="success", started_at=expired_time, completed_at=expired_time, summary={"storage_mode": "annual", "milestone_year": 2025}, ) current_snap = DataSnapshot( datasource_id=1, source="celestrak_tle", is_current=True, status="success", started_at=recent_time, completed_at=recent_time, parent_snapshot_id=None, summary={"storage_mode": "single"}, ) sqlite_db.add_all([expired_snap, milestone_snap, current_snap]) await sqlite_db.commit() current_snap.parent_snapshot_id = expired_snap.id sqlite_db.add_all( [ CollectedData( snapshot_id=expired_snap.id, source="celestrak_tle", source_id="sat-1", entity_key="celestrak_tle:sat-1", data_type="satellite_tle", is_current=False, extra_data={}, ), CollectedData( snapshot_id=milestone_snap.id, source="top500", source_id="t-1", entity_key="top500:t-1", data_type="supercomputer", is_current=False, extra_data={}, ), CollectedData( snapshot_id=current_snap.id, source="celestrak_tle", source_id="sat-1", entity_key="celestrak_tle:sat-1", data_type="satellite_tle", is_current=True, extra_data={}, ), BGPObservation( source="ris_live_bgp", prefix="1.1.1.0/24", event_type="announcement", observed_at=old_bgp_time, ), BGPObservation( source="ris_live_bgp", prefix="8.8.8.0/24", event_type="announcement", observed_at=recent_time, ), EarthNewsItem( id="rss:old", title="Old RSS", url="https://example.invalid/1", region="global", latitude=0.0, longitude=0.0, location_label="Global", published_at=expired_time, ), EarthNewsItem( id="manual:editorial-old", title="Manual Preserved", url="https://example.invalid/2", region="global", latitude=0.0, longitude=0.0, location_label="Global", published_at=expired_time, ), SystemLog(source="api", level="info", message="old log", occurred_at=expired_time), SystemLog(source="api", level="info", message="fresh log", occurred_at=recent_time), VesselPosition( mmsi=413000999, lat=30.0, lon=120.0, received_at=now - timedelta(hours=36), ), VesselPosition( mmsi=413000999, lat=30.5, lon=120.5, received_at=now - timedelta(hours=1), ), ObservabilityEvent( source="api", level="info", message="old event", fingerprint="fp-old", occurred_at=expired_time, ), ] ) await sqlite_db.commit() # Safety gate: auto_prune_enabled=False performs zero deletes. await save_storage_policy( sqlite_db, {"default_mode": "single", "overrides": {}, "auto_prune_enabled": False}, sync_system_retention=False, ) skipped = await run_storage_retention_maintenance(sqlite_db, now=now) assert skipped["skipped"] is True assert await sqlite_db.scalar(select(func.count(DataSnapshot.id))) == 3 # Turn auto_prune_enabled=True -> expired history pruned, current + annual milestone + manual news kept! await save_storage_policy( sqlite_db, {"default_mode": "single", "overrides": {}, "auto_prune_enabled": True}, sync_system_retention=False, ) pruned = await run_storage_retention_maintenance(sqlite_db, now=now) assert pruned["skipped"] is False assert pruned["deleted"]["data_snapshots"] == 1 assert pruned["deleted"]["collected_data"] == 1 assert pruned["deleted"]["bgp_observations"] == 1 assert pruned["deleted"]["vessel_positions"] == 1 assert pruned["deleted"]["earth_news_items"] == 1 assert pruned["deleted"]["system_logs"] == 1 assert pruned["deleted"]["observability_events"] == 1 remaining_snap_ids = { s.id for s in (await sqlite_db.scalars(select(DataSnapshot))).all() } assert remaining_snap_ids == {milestone_snap.id, current_snap.id} assert await sqlite_db.get(EarthNewsItem, "manual:editorial-old") is not None @pytest.mark.asyncio async def test_settings_storage_policy_and_collector_endpoints(sqlite_db): sqlite_db.add( DataSource( id=1, name="TOP500", source="top500", module="L1", priority="P0", frequency_minutes=1440, collector_class="top500", is_active=True, ) ) sqlite_db.add( DataSource( id=2, name="IPtoASN", source="iptoasn_prefix_geo", module="L3", priority="P1", frequency_minutes=1440, collector_class="iptoasn_prefix_geo", is_active=True, ) ) sqlite_db.add(SystemSetting(category="system", payload={"data_retention_days": 30})) await save_storage_policy( sqlite_db, DEFAULT_STORAGE_POLICY, sync_system_retention=False, ) async def override_get_db(): yield sqlite_db def override_get_current_user(): return User( id=1, username="admin", email="admin@example.com", password_hash="x", role="admin", is_active=True, ) app.dependency_overrides[get_db] = override_get_db app.dependency_overrides[get_current_user] = override_get_current_user transport = ASGITransport(app=app) try: async with AsyncClient(transport=transport, base_url="http://test") as client: with ( patch("app.api.v1.settings.sync_datasource_job", new=AsyncMock(return_value=True)), patch("app.api.v1.settings.record_audit_log", new=AsyncMock()), ): get_resp = await client.get("/api/v1/settings/storage-policy") assert get_resp.status_code == 200 body = get_resp.json()["storage_policy"] assert body["master_state"] == "partial" assert body["effective_modes"] == {"iptoasn_prefix_geo": "single", "top500": "annual"} # Update storage policy retention -> syncs system.data_retention_days cleanly. put_resp = await client.put( "/api/v1/settings/storage-policy", json={"history_retention_days": 60, "auto_prune_enabled": False}, ) assert put_resp.status_code == 200 assert put_resp.json()["storage_policy"]["history_retention_days"] == 60 sys_resp = await client.get("/api/v1/settings/system") assert sys_resp.json()["system"]["data_retention_days"] == 60 # Update collector snapshot_mode via /settings/collectors/{id} col_resp = await client.put( "/api/v1/settings/collectors/2", json={ "is_active": True, "priority": "P1", "frequency_minutes": 1440, "snapshot_mode": "history", }, ) assert col_resp.status_code == 200 col_payload = col_resp.json() assert col_payload["collector"]["snapshot_mode"] == "history" assert col_payload["collector"]["snapshot_overridden"] is True assert col_payload["collector"]["high_volume_warning"]["estimated_monthly_growth"] assert col_payload["storage_policy"]["snapshot_enabled_count"] == 2 # Switching to all_single activates global_single_lock and blocks single-source history/annual overrides. lock_resp = await client.put( "/api/v1/settings/storage-policy", json={"action": "all_single"}, ) assert lock_resp.status_code == 200 lock_body = lock_resp.json()["storage_policy"] assert lock_body["global_single_lock"] is True assert lock_body["master_state"] == "off" assert lock_body["overrides"] == {} rejected_policy = await client.put( "/api/v1/settings/storage-policy", json={"source_mode": {"iptoasn_prefix_geo": "history"}}, ) assert rejected_policy.status_code == 409 rejected_col = await client.put( "/api/v1/settings/collectors/2", json={ "is_active": True, "priority": "P1", "frequency_minutes": 1440, "snapshot_mode": "history", }, ) assert rejected_col.status_code == 409 # Saving non-snapshot fields with snapshot_mode='single' while locked still succeeds cleanly. allowed_col = await client.put( "/api/v1/settings/collectors/2", json={ "is_active": True, "priority": "P0", "frequency_minutes": 720, "snapshot_mode": "single", }, ) assert allowed_col.status_code == 200 assert allowed_col.json()["collector"]["snapshot_locked"] is True # Switching back to recommended_default unlocks per-source configuration cleanly. unlock_resp = await client.put( "/api/v1/settings/storage-policy", json={"action": "recommended_default"}, ) assert unlock_resp.status_code == 200 assert unlock_resp.json()["storage_policy"]["global_single_lock"] is False finally: app.dependency_overrides.clear() @pytest.mark.asyncio async def test_telegeography_sample_fallback_preserves_existing_records(sqlite_db, monkeypatch): await save_storage_policy( sqlite_db, {"default_mode": "single", "global_single_lock": True, "overrides": {}}, sync_system_retention=False, ) monkeypatch.setattr(collector_registry, "is_active", lambda _name: True) seed_snap = DataSnapshot( datasource_id=1, source="telegeography_cables", snapshot_key="telegeography_cables:seed", status="success", is_current=True, record_count=2, completed_at=datetime.now(UTC) - timedelta(hours=2), summary={"created": 2, "storage_mode": "single"}, ) sqlite_db.add(seed_snap) await sqlite_db.commit() sqlite_db.add_all( [ CollectedData( snapshot_id=seed_snap.id, source="telegeography_cables", source_id="real_1", entity_key="telegeography_cables:real_1", data_type="submarine_cable", name="REAL CABLE 1", is_current=True, extra_data={"status": "active"}, ), CollectedData( snapshot_id=seed_snap.id, source="telegeography_cables", source_id="real_2", entity_key="telegeography_cables:real_2", data_type="submarine_cable", name="REAL CABLE 2", is_current=True, extra_data={"status": "active"}, ), ] ) await sqlite_db.commit() async def failing_get(*_args, **_kwargs): raise RuntimeError("upstream unavailable") monkeypatch.setattr("app.services.collectors.telegeography.httpx.AsyncClient.get", failing_get) collector = TeleGeographyCableCollector() res = await collector.run(sqlite_db) assert res["status"] == "failed" rows = list( ( await sqlite_db.scalars( select(CollectedData) .where( CollectedData.source == "telegeography_cables", CollectedData.is_current.is_(True), ) .order_by(CollectedData.id.asc()) ) ).all() ) assert [row.source_id for row in rows] == ["real_1", "real_2"] reloaded_snap = await sqlite_db.get(DataSnapshot, seed_snap.id) assert reloaded_snap is not None assert reloaded_snap.status == "success" assert reloaded_snap.is_current is True @pytest.mark.asyncio async def test_midflight_switch_to_all_single_prevents_history_snapshot(sqlite_db, monkeypatch): monkeypatch.setattr(collector_registry, "is_active", lambda _name: True) await save_storage_policy( sqlite_db, {"default_mode": "history", "overrides": {}}, sync_system_retention=False, ) seed = _SampleCollector([{"source_id": "x1", "name": "Item 1", "value": 1}]) assert (await seed.run(sqlite_db))["status"] == "success" assert await sqlite_db.scalar(select(func.count(DataSnapshot.id))) == 1 # Case A: switch to all_single while task is inside fetch(). class _MidFetchSwitchCollector(_SampleCollector): async def fetch(self): await save_storage_policy( sqlite_db, apply_global_snapshot_action(await get_storage_policy(sqlite_db), "all_single"), sync_system_retention=False, ) return [{"source_id": "x1", "name": "Item 1", "value": 2}] mid_fetch = _MidFetchSwitchCollector() res_a = await mid_fetch.run(sqlite_db) assert res_a["status"] == "success" assert await sqlite_db.scalar(select(func.count(DataSnapshot.id))) == 1 current_val = ( await sqlite_db.scalars( select(CollectedData).where( CollectedData.source == "sample_test_collector", CollectedData.is_current.is_(True), ) ) ).all() assert len(current_val) == 1 assert current_val[0].extra_data["value"] == 2 # Case B: switch to all_single right after _create_snapshot() (between snapshot create and _save_data). await save_storage_policy( sqlite_db, {"default_mode": "history", "global_single_lock": False, "overrides": {}}, sync_system_retention=False, ) class _LateSwitchCollector(_SampleCollector): async def _save_data(self, db, data, task_id=None, snapshot_id=None): await save_storage_policy( db, apply_global_snapshot_action(await get_storage_policy(db), "all_single"), sync_system_retention=False, ) return await super()._save_data(db, data, task_id=task_id, snapshot_id=snapshot_id) late = _LateSwitchCollector([{"source_id": "x1", "name": "Item 1", "value": 3}]) res_b = await late.run(sqlite_db) assert res_b["status"] == "success" assert await sqlite_db.scalar(select(func.count(DataSnapshot.id))) == 1 current_snap = ( await sqlite_db.scalars( select(DataSnapshot).where( DataSnapshot.source == "sample_test_collector", DataSnapshot.is_current.is_(True), ) ) ).one() assert current_snap.summary["storage_mode"] == "single" @pytest.mark.asyncio async def test_history_mode_dedupes_identical_runs_and_preserves_current_on_failure( sqlite_db, monkeypatch ): monkeypatch.setattr(collector_registry, "is_active", lambda _name: True) await save_storage_policy( sqlite_db, {"default_mode": "history", "global_single_lock": False, "overrides": {}}, sync_system_retention=False, ) payload_v1 = [ {"source_id": "h1", "name": "Node 1", "value": 10}, {"source_id": "h2", "name": "Node 2", "value": 20}, ] c1 = _SampleCollector(payload_v1, full_reconcile=True) assert (await c1.run(sqlite_db))["status"] == "success" # Identical repeat run in history mode must not create a second snapshot or duplicate rows. c2 = _SampleCollector(payload_v1, full_reconcile=True) res2 = await c2.run(sqlite_db) assert res2["status"] == "success" assert c2._last_save_summary == {"created": 0, "updated": 0, "unchanged": 2, "deleted": 0} assert await sqlite_db.scalar(select(func.count(DataSnapshot.id))) == 1 assert await sqlite_db.scalar(select(func.count(CollectedData.id))) == 2 s1 = (await sqlite_db.scalars(select(DataSnapshot))).one() assert s1.status == "success" assert s1.is_current is True # Failed save in history mode with changed data keeps S1 current and marks failed snapshot is_current=False. c_fail = _SampleCollector( [ {"source_id": "h1", "name": "Node 1", "value": 99}, {"source_id": "h2", "name": "Node 2", "value": 20}, ], full_reconcile=True, ) monkeypatch.setattr( c_fail, "_save_data", AsyncMock(side_effect=RuntimeError("simulated disk full")), ) res_fail = await c_fail.run(sqlite_db) assert res_fail["status"] == "failed" snapshots = list((await sqlite_db.scalars(select(DataSnapshot).order_by(DataSnapshot.id.asc()))).all()) assert len(snapshots) == 2 assert snapshots[0].id == s1.id assert snapshots[0].status == "success" assert snapshots[0].is_current is True assert snapshots[1].status == "failed" assert snapshots[1].is_current is False current_rows = list( ( await sqlite_db.scalars( select(CollectedData) .where(CollectedData.is_current.is_(True)) .order_by(CollectedData.id.asc()) ) ).all() ) assert [(r.snapshot_id, r.source_id, r.extra_data["value"]) for r in current_rows] == [ (s1.id, "h1", 10), (s1.id, "h2", 20), ] # Changed run that succeeds creates version 2 cleanly and promotes it. c3 = _SampleCollector( [ {"source_id": "h1", "name": "Node 1", "value": 99}, {"source_id": "h2", "name": "Node 2", "value": 20}, ], full_reconcile=True, ) assert (await c3.run(sqlite_db))["status"] == "success" final_snaps = list((await sqlite_db.scalars(select(DataSnapshot).order_by(DataSnapshot.id.asc()))).all()) assert [(s.status, s.is_current) for s in final_snaps] == [ ("success", False), ("failed", False), ("success", True), ] def test_earth_notify_trigger_avoids_id_using_clause(): assert "USING (id)" not in PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL assert "IF TG_TABLE_NAME = 'earth_news_items' THEN" in PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL assert "current_row.row_data->>'id' = previous_row.row_data->>'id'" in PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL @pytest.mark.asyncio async def test_publish_time_switch_to_all_single_downgrades_without_third_snapshot( sqlite_db, monkeypatch ): monkeypatch.setattr(collector_registry, "is_active", lambda _name: True) await save_storage_policy( sqlite_db, {"default_mode": "history", "global_single_lock": False, "overrides": {}}, sync_system_retention=False, ) c1 = _SampleCollector([{"source_id": "p1", "name": "v1"}], full_reconcile=True) c2 = _SampleCollector([{"source_id": "p1", "name": "v2"}], full_reconcile=True) assert (await c1.run(sqlite_db))["status"] == "success" assert (await c2.run(sqlite_db))["status"] == "success" assert await sqlite_db.scalar(select(func.count(DataSnapshot.id))) == 2 class _PauseBeforePublishCollector(_SampleCollector): async def _finalize_snapshot_after_save(self, db, **kwargs): if kwargs.get("storage_mode") == "history": await save_storage_policy( db, apply_global_snapshot_action(await get_storage_policy(db), "all_single"), sync_system_retention=False, ) return await super()._finalize_snapshot_after_save(db, **kwargs) c3 = _PauseBeforePublishCollector([{"source_id": "p1", "name": "v3"}], full_reconcile=True) res3 = await c3.run(sqlite_db) assert res3["status"] == "success" all_snaps = list((await sqlite_db.scalars(select(DataSnapshot).order_by(DataSnapshot.id.asc()))).all()) assert len(all_snaps) == 2 assert all_snaps[-1].status == "success" assert all_snaps[-1].is_current is True assert all_snaps[-1].summary["storage_mode"] == "single" current_rows = list( ( await sqlite_db.scalars( select(CollectedData).where( CollectedData.source == "sample_test_collector", CollectedData.is_current.is_(True), ) ) ).all() ) assert len(current_rows) == 1 assert current_rows[0].name == "v3" def test_storage_policy_publish_constraint_trigger_ddl(): assert "pg_advisory_xact_lock_shared(17001614, 2)" in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL assert "FOR SHARE" in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL assert "planet_storage_policy_single_violation" in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL joined_triggers = "\n".join(PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS) assert "DEFERRABLE INITIALLY DEFERRED" in joined_triggers assert "tr_planet_enforce_storage_policy_publish" in joined_triggers @pytest.mark.asyncio async def test_storage_retention_maintenance_prunes_expired_ais_raw_observations(sqlite_db): now = datetime(2026, 6, 1, 12, 0, tzinfo=UTC) expired_time = now - timedelta(days=45) fresh_time = now - timedelta(days=5) sqlite_db.add_all( [ AISRawObservation( source="barentswatch_vessels", target_schema="vessel_ais", entity_key="257000111", delivery_mode="polling", transport="http", observation_hash="old-ais-hash", observed_at=expired_time, collected_at=expired_time, raw_payload={"mmsi": 257000111}, normalized_payload={"mmsi": 257000111}, ), AISRawObservation( source="barentswatch_vessels", target_schema="vessel_ais", entity_key="257000111", delivery_mode="polling", transport="http", observation_hash="fresh-ais-hash", observed_at=fresh_time, collected_at=fresh_time, raw_payload={"mmsi": 257000111}, normalized_payload={"mmsi": 257000111}, ), ] ) await save_storage_policy( sqlite_db, { "default_mode": "single", "overrides": {}, "history_retention_days": 30, "auto_prune_enabled": True, }, sync_system_retention=False, ) pruned = await run_storage_retention_maintenance(sqlite_db, now=now) assert pruned["skipped"] is False assert pruned["deleted"]["ais_raw_observations"] == 1 remaining_hashes = list( (await sqlite_db.scalars(select(AISRawObservation.observation_hash))).all() ) assert remaining_hashes == ["fresh-ais-hash"] @pytest.mark.asyncio async def test_settings_mutation_endpoints_require_admin_and_preserve_global_lock(sqlite_db): sqlite_db.add( DataSource( id=2, name="IPtoASN", source="iptoasn_prefix_geo", module="L3", priority="P1", frequency_minutes=1440, collector_class="iptoasn_prefix_geo", is_active=True, ) ) sqlite_db.add(SystemSetting(category="system", payload={"data_retention_days": 30})) await save_storage_policy( sqlite_db, { "default_mode": "single", "overrides": {}, "global_single_lock": True, "history_retention_days": 30, }, sync_system_retention=False, ) active_role = {"role": "viewer"} async def override_get_db(): yield sqlite_db def override_get_current_user(): return User( id=1, username="tester", email="tester@example.com", password_hash="x", role=active_role["role"], is_active=True, ) app.dependency_overrides[get_db] = override_get_db app.dependency_overrides[get_current_user] = override_get_current_user transport = ASGITransport(app=app) try: async with AsyncClient(transport=transport, base_url="http://test") as client: with ( patch("app.api.v1.settings.sync_datasource_job", new=AsyncMock(return_value=True)), patch("app.api.v1.settings.record_audit_log", new=AsyncMock()), ): for method_url, body in ( ("/api/v1/settings/storage-policy", {"history_retention_days": 17}), ("/api/v1/settings/system", {"data_retention_days": 21}), ( "/api/v1/settings/collectors/2", { "is_active": True, "priority": "P0", "frequency_minutes": 720, "snapshot_mode": "single", }, ), ("/api/v1/settings/security", {"session_timeout": 30}), ("/api/v1/settings/notifications", {"email_enabled": False}), ("/api/v1/settings/tv", {"auto_rotate": False}), ): resp = await client.put(method_url, json=body) assert resp.status_code == 403, f"expected 403 for {method_url}, got {resp.status_code}" active_role["role"] = "admin" ret_resp = await client.put( "/api/v1/settings/storage-policy", json={"history_retention_days": 17}, ) assert ret_resp.status_code == 200 ret_policy = ret_resp.json()["storage_policy"] assert ret_policy["history_retention_days"] == 17 assert ret_policy["global_single_lock"] is True assert ret_policy["default_mode"] == "single" sys_resp = await client.put( "/api/v1/settings/system", json={"data_retention_days": 21}, ) assert sys_resp.status_code == 200 policy_after_sys = await get_storage_policy(sqlite_db) assert policy_after_sys["history_retention_days"] == 21 assert policy_after_sys["global_single_lock"] is True assert policy_after_sys["default_mode"] == "single" rejected_col = await client.put( "/api/v1/settings/collectors/2", json={ "is_active": False, "priority": "P0", "frequency_minutes": 15, "snapshot_mode": "history", }, ) assert rejected_col.status_code == 409 await sqlite_db.rollback() ds_after = await sqlite_db.get(DataSource, 2) assert ds_after is not None assert ds_after.priority == "P1" assert ds_after.frequency_minutes == 1440 assert ds_after.is_active is True finally: app.dependency_overrides.clear() @pytest.mark.asyncio async def test_delete_same_name_datasource_config_preserves_sibling_collected_data(sqlite_db): cfg1 = DataSourceConfig( id=101, name="shared_custom_feed", source_type="api", endpoint="https://example.invalid/feed1", ) cfg2 = DataSourceConfig( id=102, name="shared_custom_feed", source_type="api", endpoint="https://example.invalid/feed2", ) sqlite_db.add_all( [ cfg1, cfg2, CollectedData( source="shared_custom_feed", source_id="row-a", entity_key="datasource_config:101:row-a", data_type="geo_points", name="From 101", is_current=True, collected_at=datetime.now(UTC), ), CollectedData( source="shared_custom_feed", source_id="row-a", entity_key="datasource_config:102:row-a", data_type="geo_points", name="From 102", is_current=True, collected_at=datetime.now(UTC), ), ] ) await sqlite_db.commit() admin = User( id=1, username="admin", email="admin@example.com", password_hash="x", role="admin", is_active=True, ) res = await delete_config( config_id=101, delete_mappings=True, delete_source_data=True, current_user=admin, db=sqlite_db, ) assert res["deleted_records"]["collected_data"] == 1 remaining_keys = list((await sqlite_db.scalars(select(CollectedData.entity_key))).all()) assert remaining_keys == ["datasource_config:102:row-a"]