"""v1.6.3 realtime guards: thread-free SSE fan-out and material evidence events.""" from __future__ import annotations import asyncio import threading from datetime import UTC, datetime from pathlib import Path from app import store as store_module from app.events import EventBus, next_event from app.models import HealthStatus, ProbeResult, ServiceCreate, ServiceKind from app.store import Store def test_waiting_subscribers_do_not_hold_threads_and_receive_cross_thread_publishes() -> None: async def scenario() -> None: bus = EventBus() subscriptions = [bus.subscribe() for _ in range(25)] threads_before = threading.active_count() waiters = [asyncio.create_task(next_event(item, timeout=2.0)) for item in subscriptions] await asyncio.sleep(0.05) # 25 parked SSE clients must not occupy 25 executor threads. assert threading.active_count() <= threads_before + 1 publisher = threading.Thread(target=bus.publish, args=({"event_type": "probe.completed"},)) publisher.start() publisher.join() received = await asyncio.gather(*waiters) assert all(item == {"event_type": "probe.completed"} for item in received) assert bus.subscriber_count == 25 for item in subscriptions: bus.unsubscribe(item) assert bus.subscriber_count == 0 asyncio.run(scenario()) def test_idle_stream_times_out_to_keepalive_and_overflow_keeps_newest() -> None: async def scenario() -> None: bus = EventBus(max_queue_size=2) subscription = bus.subscribe() assert await next_event(subscription, timeout=0.01) is None for index in range(5): bus.publish({"event_type": "probe.completed", "n": index}) await asyncio.sleep(0) # let call_soon_threadsafe deliveries run first = await next_event(subscription, timeout=0.1) second = await next_event(subscription, timeout=0.1) assert [first["n"], second["n"]] == [3, 4] asyncio.run(scenario()) def test_repeated_probe_with_only_latency_change_is_not_a_material_evidence_event( tmp_path: Path, monkeypatch ) -> None: store = Store(str(tmp_path / "servicemap.db")) service = store.create_service( ServiceCreate(name="API", kind=ServiceKind.HTTP, url="https://api.test") ) published: list[dict[str, object]] = [] monkeypatch.setattr(store_module.event_bus, "publish", published.append) for index, latency in enumerate((12.0, 48.0, 7.5)): store.save_probe( ProbeResult( id=f"probe-{index}", service_id=service.id, status=HealthStatus.HEALTHY, latency_ms=latency, detail="HTTP 200", checked_at=datetime.now(UTC), ) ) evidence_events = [item for item in published if item["event_type"] == "health.evidence_changed"] # The first claim is new; later identical claims differ only in volatile keys. assert len(evidence_events) == 1 # Probe completion itself is still announced every time. assert sum(item["event_type"] == "probe.completed" for item in published) == 3 store.save_probe( ProbeResult( id="probe-down", service_id=service.id, status=HealthStatus.DOWN, latency_ms=None, detail="Connection refused", checked_at=datetime.now(UTC), ) ) evidence_events = [item for item in published if item["event_type"] == "health.evidence_changed"] assert len(evidence_events) == 2