Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

feat(health): report per-service dependency readiness (#1489)

Beenu Arorab9409f108084
diff --git a/apps/docs/docs/operations/ha-deployment.md b/apps/docs/docs/operations/ha-deployment.md
index 020aaea0d..e60bc99ea 100644
--- a/apps/docs/docs/operations/ha-deployment.md
+++ b/apps/docs/docs/operations/ha-deployment.md
@@ -149,6 +149,15 @@ readiness probe for `api`, `ingest`, `alert-fusion`, `agents` and `realtime`.
It used to wire `/health` for both probes, and `/health` answers 200 while the
process is alive whatever its consumer is doing.
+Readiness also reports per-service dependency keys: Fusion reports `database`,
+`lake_writer` and `kafka`; Agents and Actions report `database`; Ingest reports
+`kafka` and `graph`; Realtime reports `kafka`. A value of `false` names the
+unavailable dependency. Probes are bounded to 1.5 seconds. The ClickHouse lake
+and Neo4j graph are auxiliary projections: their loss is reported as degraded,
+but they do not remove the event pipeline from service. Postgres and the Kafka
+spine are required and fail readiness when unavailable. Realtime exposes the
+same Kafka report on `/readyz` (and keeps `/health` and `/healthz` compatible).
+
A detached replica is therefore pulled out of service but **not** killed. That
is deliberate: restarting on readiness failure turns a broker or schema fault
into a restart loop that hides the cause. What the chart does instead is
diff --git a/infra/helm/aisoc/Chart.yaml b/infra/helm/aisoc/Chart.yaml
index 891e9adda..19058d250 100644
--- a/infra/helm/aisoc/Chart.yaml
+++ b/infra/helm/aisoc/Chart.yaml
@@ -25,7 +25,7 @@ type: application
# the chart refuses grants it used to accept (see the v14.0.0 BREAKING
# section), and the chart's major is the only coordinate a consumer pulling
# `oci://ghcr.io/beenuar/charts/aisoc` sees before they install it.
-version: 7.10.0
+version: 7.10.1
# Used as the image tag wherever a `tag:` in values.yaml is left empty, so
# it has to be a tag the registry actually holds — it read "5.2.0", which
# exists for no image, so every pod of a default install would have gone to
diff --git a/infra/helm/aisoc/values.yaml b/infra/helm/aisoc/values.yaml
index ce4928e70..39fb0bc38 100644
--- a/infra/helm/aisoc/values.yaml
+++ b/infra/helm/aisoc/values.yaml
@@ -268,7 +268,7 @@ services:
replicaCount: 2
containerPort: 8085
healthCheckPath: /health
- readinessPath: /health
+ readinessPath: /readyz
service:
type: ClusterIP
port: 80
diff --git a/services/actions/app/_health.py b/services/actions/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/actions/app/_health.py
+++ b/services/actions/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/actions/app/main.py b/services/actions/app/main.py
index b6aa0ad20..90d69fae0 100644
--- a/services/actions/app/main.py
+++ b/services/actions/app/main.py
@@ -18,10 +18,12 @@ without restarting the process.
from __future__ import annotations
+import os
+
import structlog
from fastapi import FastAPI
-from app._health import install_health_routes
+from app._health import install_health_routes, register_dependency
from app.api.live_actions_router import router as live_actions_router
from app.api.replay_history_router import router as replay_history_router
from app.api.router import router as legacy_router
@@ -47,6 +49,24 @@ _mark_ready, _mark_not_ready = install_health_routes(app, service_name="aisoc-ac
app.state.mark_ready = _mark_ready
app.state.mark_not_ready = _mark_not_ready
+
+async def _database_ready() -> bool:
+ import asyncpg
+
+ dsn = (os.getenv("DATABASE_DSN") or os.getenv("DATABASE_URL") or "").strip()
+ if not dsn:
+ return False
+ for prefix in ("postgresql+asyncpg://", "postgres+asyncpg://"):
+ if dsn.startswith(prefix):
+ dsn = "postgresql://" + dsn[len(prefix) :]
+ break
+ conn = await asyncpg.connect(dsn, timeout=1.4)
+ await conn.close()
+ return True
+
+
+register_dependency(app, "database", _database_ready)
+
app.include_router(legacy_router, prefix="/api/v1")
app.include_router(live_actions_router, prefix="/api/v1")
# Gap-closure Phase 1.4: the read half of the SIEM relationship. Phase 1.1 put
diff --git a/services/agents/app/_health.py b/services/agents/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/agents/app/_health.py
+++ b/services/agents/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/agents/app/main.py b/services/agents/app/main.py
index c8ddfbdfc..0a6eebeae 100644
--- a/services/agents/app/main.py
+++ b/services/agents/app/main.py
@@ -7,7 +7,7 @@ import structlog
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
-from app._health import install_health_routes, register_subscription
+from app._health import install_health_routes, register_dependency, register_subscription
from app.api.contextual import router as contextual_router
from app.api.copilot import router as copilot_router
from app.api.explain import router as explain_router
@@ -216,6 +216,24 @@ _mark_ready, _mark_not_ready = install_health_routes(app, service_name="aisoc-ag
app.state.mark_ready = _mark_ready
app.state.mark_not_ready = _mark_not_ready
+
+async def _database_ready() -> bool:
+ import asyncpg
+
+ dsn = os.getenv("DATABASE_URL", "").strip()
+ if not dsn:
+ return False
+ for prefix in ("postgresql+asyncpg://", "postgres+asyncpg://"):
+ if dsn.startswith(prefix):
+ dsn = "postgresql://" + dsn[len(prefix) :]
+ break
+ conn = await asyncpg.connect(dsn, timeout=1.4)
+ await conn.close()
+ return True
+
+
+register_dependency(app, "database", _database_ready)
+
# CORS — the web console talks to this service directly (it does not go through
# the Next.js rewrite layer for agent endpoints because we want to stream
# NDJSON without buffering through the proxy). Origins are resolved via the
diff --git a/services/api/app/_health.py b/services/api/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/api/app/_health.py
+++ b/services/api/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/connectors/app/_health.py b/services/connectors/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/connectors/app/_health.py
+++ b/services/connectors/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/fusion/app/_health.py b/services/fusion/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/fusion/app/_health.py
+++ b/services/fusion/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/fusion/app/main.py b/services/fusion/app/main.py
index 737b2bba3..d1ecf9aa0 100644
--- a/services/fusion/app/main.py
+++ b/services/fusion/app/main.py
@@ -6,7 +6,7 @@ from typing import Any
import redis.asyncio as aioredis
from fastapi import FastAPI
-from app._health import install_health_routes, register_subscription
+from app._health import install_health_routes, register_dependency, register_subscription
from app.api.router import router, set_worker
from app.core.config import settings
from app.core.logging import configure_logging, logger
@@ -185,6 +185,7 @@ 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)
app.state.worker_task = worker_task
app.state.redis = redis_client
@@ -238,6 +239,43 @@ _mark_ready, _mark_not_ready = install_health_routes(app, service_name="aisoc-fu
app.state.mark_ready = _mark_ready
app.state.mark_not_ready = _mark_not_ready
+
+async def _postgres_ready() -> bool:
+ import asyncpg
+
+ dsn = settings.database_url
+ for prefix in ("postgresql+asyncpg://", "postgres+asyncpg://"):
+ if dsn.startswith(prefix):
+ dsn = "postgresql://" + dsn[len(prefix) :]
+ break
+ conn = await asyncpg.connect(dsn, timeout=1.4)
+ await conn.close()
+ return True
+
+
+def _clickhouse_ready() -> bool:
+ if not settings.lake_writer_enabled:
+ return False
+ from clickhouse_driver import Client
+
+ client = Client(
+ host=settings.clickhouse_host,
+ port=settings.clickhouse_port,
+ database=settings.clickhouse_database,
+ user=settings.clickhouse_user,
+ password=settings.clickhouse_password or "",
+ connect_timeout=0.7,
+ send_receive_timeout=0.7,
+ )
+ try:
+ return client.execute("SELECT 1", settings={"max_execution_time": 1}) == [(1,)]
+ finally:
+ client.disconnect()
+
+
+register_dependency(app, "database", _postgres_ready)
+register_dependency(app, "lake_writer", _clickhouse_ready, required=False)
+
app.include_router(router)
diff --git a/services/fusion/tests/test_dependency_health.py b/services/fusion/tests/test_dependency_health.py
new file mode 100644
index 000000000..f2921dbdd
--- /dev/null
+++ b/services/fusion/tests/test_dependency_health.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+import asyncio
+import time
+
+from app._health import install_health_routes, register_dependency
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+
+def test_dependency_is_reported_before_startup_finishes() -> None:
+ app = FastAPI()
+ install_health_routes(app, service_name="test")
+ register_dependency(app, "database", lambda: False)
+
+ response = TestClient(app).get("/readyz")
+
+ assert response.status_code == 503
+ assert response.json()["status"] == "starting"
+ assert response.json()["database"] is False
+
+
+def test_required_dependency_failure_returns_503_and_named_key() -> None:
+ app = FastAPI()
+ mark_ready, _ = install_health_routes(app, service_name="test")
+ register_dependency(app, "database", lambda: False)
+ mark_ready()
+
+ response = TestClient(app).get("/readyz")
+
+ assert response.status_code == 503
+ assert response.json()["database"] is False
+ assert "database" in response.json()["detached"]
+
+
+def test_optional_dependency_failure_reports_degraded_but_stays_ready() -> None:
+ app = FastAPI()
+ mark_ready, _ = install_health_routes(app, service_name="test")
+ register_dependency(app, "lake_writer", lambda: False, required=False)
+ mark_ready()
+
+ response = TestClient(app).get("/readyz")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "ready_degraded"
+ assert response.json()["lake_writer"] is False
+
+
+def test_slow_dependency_is_bounded_and_reported_down() -> None:
+ app = FastAPI()
+ mark_ready, _ = install_health_routes(app, service_name="test")
+
+ async def slow_probe() -> bool:
+ await asyncio.sleep(10)
+ return True
+
+ register_dependency(app, "database", slow_probe)
+ mark_ready()
+
+ started = time.monotonic()
+ response = TestClient(app).get("/readyz")
+
+ assert time.monotonic() - started < 2.5
+ assert response.status_code == 503
+ assert response.json()["database"] is False
+ assert response.json()["dependency_errors"]["database"] == "TimeoutError"
diff --git a/services/honeytokens/app/_health.py b/services/honeytokens/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/honeytokens/app/_health.py
+++ b/services/honeytokens/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/ingest/internal/graph/writer.go b/services/ingest/internal/graph/writer.go
index 2b7908a39..b5ff7da04 100644
--- a/services/ingest/internal/graph/writer.go
+++ b/services/ingest/internal/graph/writer.go
@@ -331,6 +331,12 @@ func newWriterFromDriver(driver Driver, cfg Config) *Writer {
return w
}
+// Ready performs a bounded caller-context connectivity check. Graph is an
+// auxiliary projection, so callers report degradation without blocking ingest.
+func (w *Writer) Ready(ctx context.Context) error {
+ return w.driver.VerifyConnectivity(ctx)
+}
+
// WriteEvent enqueues a graph projection for batched flush. NEVER blocks: if
// the queue is full we drop and increment the metric. This is the explicit
// guarantee from T1.1: graph-write failures must NOT block fusion ingest.
diff --git a/services/ingest/internal/handler/handler.go b/services/ingest/internal/handler/handler.go
index 74680c1ac..a2fbf778c 100644
--- a/services/ingest/internal/handler/handler.go
+++ b/services/ingest/internal/handler/handler.go
@@ -28,6 +28,10 @@ type GraphWriter interface {
WriteEvent(ctx context.Context, ev *graph.Event) error
}
+type graphReadiness interface {
+ Ready(context.Context) error
+}
+
// EventPublisher is the subset of *publisher.Publisher the HTTP path
// depends on. Declared as an interface for the same reason GraphWriter is:
// so a request can be driven end to end in a unit test — including which
@@ -306,8 +310,7 @@ func (h *Handler) Livez(w http.ResponseWriter, r *http.Request) {
// directly instead: /v1/graph_ws/stream answers 503 with the reason, and
// aisoc_graph_ws_source_not_resolving is the alertable signal.
func (h *Handler) Readyz(w http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
- defer cancel()
+ ctx := r.Context()
subs := h.subscriptionReport()
body := map[string]interface{}{
@@ -317,20 +320,34 @@ func (h *Handler) Readyz(w http.ResponseWriter, r *http.Request) {
// moment somebody is reading the output to find out what is wrong.
"subscriptions": subs,
"timestamp": time.Now().UTC().Format(time.RFC3339),
+ "graph": false,
}
// Named at the top level as well, so the degraded case is legible
// without reading the per-subscription map.
if degraded := degradedSubscriptions(subs); len(degraded) > 0 {
body["degraded_subscriptions"] = degraded
}
+ if graphProbe, ok := h.graph.(graphReadiness); ok {
+ graphCtx, graphCancel := context.WithTimeout(ctx, 1500*time.Millisecond)
+ if err := graphProbe.Ready(graphCtx); err == nil {
+ body["graph"] = true
+ } else {
+ body["graph_error"] = err.Error()
+ }
+ graphCancel()
+ }
if h.pub == nil {
+ body["kafka"] = false
body["status"] = "not_ready"
body["reason"] = "no kafka publisher configured"
writeJSON(w, http.StatusServiceUnavailable, body)
return
}
- if err := h.pub.Ready(ctx); err != nil {
+ kafkaCtx, kafkaCancel := context.WithTimeout(ctx, 1500*time.Millisecond)
+ defer kafkaCancel()
+ if err := h.pub.Ready(kafkaCtx); err != nil {
+ body["kafka"] = false
body["status"] = "not_ready"
body["reason"] = err.Error()
body["hint"] = "docker compose logs kafka | tail -40"
@@ -338,8 +355,9 @@ func (h *Handler) Readyz(w http.ResponseWriter, r *http.Request) {
return
}
body["status"] = "ready"
+ body["kafka"] = true
body["checks"] = map[string]string{"kafka": "reachable"}
- if _, degraded := body["degraded_subscriptions"]; degraded {
+ if _, degraded := body["degraded_subscriptions"]; degraded || body["graph"] != true {
body["status"] = "ready_degraded"
}
writeJSON(w, http.StatusOK, body)
diff --git a/services/ingest/internal/handler/readyz_test.go b/services/ingest/internal/handler/readyz_test.go
index b333987c3..d11082d70 100644
--- a/services/ingest/internal/handler/readyz_test.go
+++ b/services/ingest/internal/handler/readyz_test.go
@@ -9,14 +9,29 @@
package handler
import (
+ "context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/beenuar/aisoc/services/ingest/internal/config"
+ "github.com/beenuar/aisoc/services/ingest/internal/graph"
+ "github.com/beenuar/aisoc/services/ingest/internal/normalizer"
)
+type readyPublisher struct{ err error }
+
+func (p readyPublisher) PublishBatch(context.Context, []*normalizer.NormalizedEvent) error {
+ return nil
+}
+func (p readyPublisher) Ready(context.Context) error { return p.err }
+
+type readyGraph struct{ err error }
+
+func (g readyGraph) WriteEvent(context.Context, *graph.Event) error { return nil }
+func (g readyGraph) Ready(context.Context) error { return g.err }
+
func newReadyHandler() *Handler {
// pub is nil, so readiness short-circuits on the publisher before any
// Kafka round-trip. That is the path a test can drive deterministically,
@@ -41,6 +56,19 @@ func callReadyz(t *testing.T, h *Handler) (*httptest.ResponseRecorder, map[strin
return rec, decodeBody(t, rec)
}
+func TestReadyzGraphOutageIsReportedWithoutBlockingIngest(t *testing.T) {
+ h := New(nil, readyPublisher{}, &config.Config{})
+ h.SetGraphWriter(readyGraph{err: context.DeadlineExceeded})
+
+ rec, body := callReadyz(t, h)
+ if rec.Code != http.StatusOK || body["kafka"] != true || body["graph"] != false {
+ t.Fatalf("graph outage should degrade, not block ingest: code=%d body=%v", rec.Code, body)
+ }
+ if body["status"] != "ready_degraded" {
+ t.Fatalf("graph outage status = %v, want ready_degraded", body["status"])
+ }
+}
+
func TestReadyzNamesAnAttachedSubscription(t *testing.T) {
h := newReadyHandler()
h.RegisterSubscription("graph_ws", func() SubscriptionStatus {
@@ -48,6 +76,12 @@ func TestReadyzNamesAnAttachedSubscription(t *testing.T) {
})
_, body := callReadyz(t, h)
+ if body["kafka"] != false {
+ t.Fatalf("missing/unavailable publisher reported kafka=%v, want false", body["kafka"])
+ }
+ if body["graph"] != false {
+ t.Fatalf("unconfigured graph reported graph=%v, want false", body["graph"])
+ }
subs, ok := body["subscriptions"].(map[string]any)
if !ok {
t.Fatalf("no subscriptions block in %v", body)
diff --git a/services/mesh/app/_health.py b/services/mesh/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/mesh/app/_health.py
+++ b/services/mesh/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/osquery-tls/app/_health.py b/services/osquery-tls/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/osquery-tls/app/_health.py
+++ b/services/osquery-tls/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/purple-team/app/_health.py b/services/purple-team/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/purple-team/app/_health.py
+++ b/services/purple-team/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.ts
index ef3e42783..63cebfd01 100644
--- a/services/realtime/src/index.ts
+++ b/services/realtime/src/index.ts
@@ -845,6 +845,7 @@ const reportHealth = (_req: express.Request, res: express.Response) => {
status: detached.length > 0 ? 'degraded' : 'healthy',
service: 'aisoc-realtime',
clients: wss.clients.size,
+ kafka: detached.length === 0,
// Reported whether or not anything is wrong, so a healthy answer says
// which subscriptions were checked rather than only that none failed.
subscriptions: [...subscriptions.entries()].map(([name, state]) => ({
@@ -857,6 +858,7 @@ const reportHealth = (_req: express.Request, res: express.Response) => {
};
app.get('/health', reportHealth);
app.get('/healthz', reportHealth);
+app.get('/readyz', reportHealth);
// --- Start ---
// Bind to "::" so we are reachable over Fly.io's 6PN private network (IPv6).
diff --git a/services/slack-bot/app/_health.py b/services/slack-bot/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/slack-bot/app/_health.py
+++ b/services/slack-bot/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/teams-bot/app/_health.py b/services/teams-bot/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/teams-bot/app/_health.py
+++ b/services/teams-bot/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/threatintel/app/_health.py b/services/threatintel/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/threatintel/app/_health.py
+++ b/services/threatintel/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe
diff --git a/services/ueba/app/_health.py b/services/ueba/app/_health.py
index 0acb9e4da..b273ae8ea 100644
--- a/services/ueba/app/_health.py
+++ b/services/ueba/app/_health.py
@@ -94,6 +94,8 @@ gate that every service has one and wires it in.
from __future__ import annotations
+import asyncio
+import inspect
import json
from collections.abc import Callable
from typing import Any
@@ -105,6 +107,31 @@ from fastapi import FastAPI, Response
#: module global because a module global is shared by every app in the
#: process, which makes two test clients interfere.
_STATE_ATTR = "health_subscriptions"
+_DEPENDENCIES_ATTR = "health_dependencies"
+
+
+async def _run_dependency(probe: Callable[[], Any]) -> tuple[bool, str | None]:
+ """Run one dependency probe with a hard 1.5 second wall-clock budget."""
+
+ async def invoke() -> Any:
+ result = probe() if inspect.iscoroutinefunction(probe) else await asyncio.to_thread(probe)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ try:
+ result = await asyncio.wait_for(invoke(), timeout=1.5)
+ return bool(result), None if result else "unavailable"
+ except Exception as exc: # noqa: BLE001 — probes must not take down readiness
+ return False, type(exc).__name__
+
+
+def register_dependency(app: FastAPI, name: str, probe: Callable[[], Any], *, required: bool = True) -> None:
+ """Report a bounded dependency check under its stable top-level JSON key."""
+ dependencies = getattr(app.state, _DEPENDENCIES_ATTR, None)
+ if dependencies is None: # pragma: no cover
+ raise RuntimeError("register_dependency requires install_health_routes(app) first")
+ dependencies[name] = (probe, required)
def _probe_detached(probes: dict[str, Callable[[], bool]]) -> list[str]:
@@ -155,7 +182,9 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
"""
state: dict[str, bool] = {"ready": False}
probes: dict[str, Callable[[], bool]] = {}
+ dependencies: dict[str, tuple[Callable[[], Any], bool]] = {}
setattr(app.state, _STATE_ATTR, probes)
+ setattr(app.state, _DEPENDENCIES_ATTR, dependencies)
@app.get(
"/livez",
@@ -174,15 +203,29 @@ def install_health_routes(app: FastAPI, *, service_name: str) -> tuple[Callable[
body: dict[str, Any] = {"status": "ready", "service": service_name}
status_code = 200
+ detached = _probe_detached(probes) if state["ready"] else []
+ results = await asyncio.gather(*(_run_dependency(probe) for probe, _required in dependencies.values()))
+ dependency_errors: dict[str, str] = {}
+ degraded = False
+ for (name, (_probe, required)), (healthy, detail) in zip(dependencies.items(), results, strict=True):
+ body[name] = healthy
+ if not healthy:
+ degraded = True
+ if detail:
+ dependency_errors[name] = detail
+ if required:
+ detached.append(name)
+ if dependency_errors:
+ body["dependency_errors"] = dependency_errors
if not state["ready"]:
body["status"] = "starting"
status_code = 503
- else:
- detached = _probe_detached(probes)
- if detached:
- body["status"] = "degraded"
- body["detached"] = detached
- status_code = 503
+ elif detached:
+ body["status"] = "degraded"
+ body["detached"] = sorted(detached)
+ status_code = 503
+ elif degraded:
+ body["status"] = "ready_degraded"
# Named subscriptions are reported either way, so a 200 says which
# ones were checked rather than only that nothing was wrong. A probe