Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(fusion): readiness must ask the broker, not ask the loop whether it is looping (#1446) (#1494)
Beenu Arorac6cfc01bf6e3
diff --git a/services/fusion/app/main.py b/services/fusion/app/main.pyindex b38721c08..6be90a8d2 100644--- a/services/fusion/app/main.py+++ b/services/fusion/app/main.py@@ -219,7 +219,13 @@ async def lifespan(app: FastAPI):worker_task = asyncio.create_task(worker.start())worker_task.add_done_callback(_log_worker_exit)register_subscription(app, "alerts+raw_events", lambda: worker.attached)- register_dependency(app, "kafka", lambda: worker.attached)+ # Two different questions, which is why they are two probes and not one+ # flag read twice. The subscription above is "am I consuming"; the+ # dependency below is "can I reach the broker", and only the second can+ # describe an outage -- `attached` stays true across one, because+ # aiokafka's retry lives inside `__anext__` and the `async for` never+ # exits. See `FusionWorker.broker_reachable`.+ register_dependency(app, "kafka", worker.broker_reachable)app.state.worker_task = worker_taskapp.state.redis = redis_clientdiff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.pyindex 2e30323a2..2c0c658a1 100644--- a/services/fusion/app/workers/consumer.py+++ b/services/fusion/app/workers/consumer.py@@ -201,6 +201,38 @@ class FusionWorker:"""return self._attached+ async def broker_reachable(self) -> bool:+ """Ask the broker, instead of asking the loop whether it is still looping.++ :attr:`attached` answers "is the consume loop iterating", and under+ aiokafka it keeps answering yes while the broker is gone: the retry+ lives inside ``__anext__``, so the ``async for`` never exits and the+ flag never clears. The weekly chaos ``kafka`` leg measured exactly+ that -- fusion logged ``NodeNotReadyError`` and+ ``GroupCoordinatorNotAvailableError`` continuously for the whole+ outage while ``/readyz`` answered **200** with ``kafka: true``. That+ is the UEBA failure shape with the loop still alive: a consumer+ attached to nothing, indistinguishable from one on a quiet topic, and+ a load balancer with no reason to route away from it.++ So the ``kafka`` *dependency* is this, and the ``alerts+raw_events``+ *subscription* stays :attr:`attached`. They are different questions --+ "can I reach the broker" and "am I consuming" -- and a readiness body+ that answers only the second cannot describe an unreachable broker.++ ``fetch_all_metadata`` (which ``topics()`` drives) builds its own+ ``ClusterMetadata``, so a probe cancelled by the caller's deadline+ cannot corrupt the client's shared view of the cluster. The caller+ (``app/_health.py``) bounds this at 1.5 s and treats a raise as+ "not reachable", which is the honest reading: if asking whether the+ broker is there is itself unanswerable, the answer is not yes.+ """+ consumer = self._consumer+ if consumer is None:+ return False+ await consumer.topics()+ return True+@propertydef durable_capture(self) -> bool:"""Whether a committed offset implies a durable capture on failure.diff --git a/services/fusion/tests/test_dependency_health.py b/services/fusion/tests/test_dependency_health.pyindex f2921dbdd..027df4924 100644--- a/services/fusion/tests/test_dependency_health.py+++ b/services/fusion/tests/test_dependency_health.py@@ -4,6 +4,7 @@ import asyncioimport timefrom app._health import install_health_routes, register_dependency+from app.workers.consumer import FusionWorkerfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -64,3 +65,94 @@ def test_slow_dependency_is_bounded_and_reported_down() -> None:assert response.status_code == 503assert response.json()["database"] is Falseassert response.json()["dependency_errors"]["database"] == "TimeoutError"+++class _StubConsumer:+ """Stands in for ``AIOKafkaConsumer`` at exactly one method.++ Deliberately minimal. The thing under test is which *question* fusion+ asks about Kafka, not aiokafka's metadata path: a double that answered+ `topics()` cheerfully while modelling nothing else would be the "the test+ double was more capable than the real thing" trap, so this one only ever+ does what a real broker does on each side of the split -- answer, or+ raise the error the live chaos run recorded.+ """++ def __init__(self, *, error: Exception | None = None) -> None:+ self._error = error+ self.asked = 0++ async def topics(self) -> set[str]:+ self.asked += 1+ if self._error is not None:+ raise self._error+ return {"aisoc.alerts.raw", "aisoc.raw_events"}+++def _worker_with(consumer: _StubConsumer | None, *, attached: bool) -> FusionWorker:+ """A worker with its Kafka state set, without building the whole engine."""+ worker = FusionWorker.__new__(FusionWorker)+ worker._consumer = consumer+ worker._attached = attached+ return worker+++def test_kafka_readiness_reports_down_while_the_loop_is_still_attached() -> None:+ """The defect the weekly chaos `kafka` leg measured, pinned.++ ``attached`` answers "is the consume loop iterating", and aiokafka keeps+ it true across a broker outage because the retry lives inside+ ``__anext__``. During the outage fusion logged ``NodeNotReadyError``+ continuously while ``/readyz`` answered 200 with ``kafka: true`` -- a+ consumer attached to nothing, indistinguishable from one on a quiet+ topic. Readiness has to ask the broker.+ """+ consumer = _StubConsumer(error=RuntimeError("NodeNotReadyError: node id 1"))+ worker = _worker_with(consumer, attached=True)++ app = FastAPI()+ mark_ready, _ = install_health_routes(app, service_name="aisoc-fusion")+ register_dependency(app, "kafka", worker.broker_reachable)+ mark_ready()++ response = TestClient(app).get("/readyz")++ # The flag the old probe read is still true: without asking the broker+ # there is nothing here to notice.+ assert worker.attached is True+ assert consumer.asked == 1, "readiness did not ask the broker at all"+ assert response.status_code == 503+ assert response.json()["kafka"] is False+++def test_kafka_readiness_stays_up_while_the_broker_answers() -> None:+ """The positive control: a working broker must not be reported as down.++ A fail-closed probe that is stuck closed reads as working caution, and+ would take fusion out of the load balancer on every healthy deployment.+ """+ consumer = _StubConsumer()+ worker = _worker_with(consumer, attached=True)++ app = FastAPI()+ mark_ready, _ = install_health_routes(app, service_name="aisoc-fusion")+ register_dependency(app, "kafka", worker.broker_reachable)+ mark_ready()++ response = TestClient(app).get("/readyz")++ assert consumer.asked == 1+ assert response.status_code == 200+ assert response.json()["kafka"] is True+++def test_kafka_readiness_is_down_before_the_consumer_exists() -> None:+ """No consumer is not a reachable broker, and must not read as one."""+ worker = _worker_with(None, attached=False)++ app = FastAPI()+ mark_ready, _ = install_health_routes(app, service_name="aisoc-fusion")+ register_dependency(app, "kafka", worker.broker_reachable)+ mark_ready()++ assert TestClient(app).get("/readyz").json()["kafka"] is False