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(phase-3.2): Postgres-outage chaos gate (fail-soft + self-heal) (#426)

Beenu Arora4fdee2c9f8cf
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index e0b1dbe3c..e885d39df 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -7,9 +7,12 @@ name: Integration
# spine — raw vendor event → ingest (OCSF normalize) → Kafka →
# fusion (promote + dedup + correlate) → fused topic →
# realtime WebSocket frame → Postgres alert row →
-# GET /api/v1/alerts. Plus duplicate suppression and a
-# chaos step (kill the fusion consumer, produce, restart,
-# assert recovery with zero event loss).
+# GET /api/v1/alerts. Plus duplicate suppression and two
+# chaos steps: (a) kill the fusion consumer, produce,
+# restart, assert recovery with zero event loss; and
+# (b) kill Postgres mid-stream, assert fusion degrades
+# fail-soft without crashing, then self-heals persistence
+# once Postgres returns.
# migrations — the API's SQL migration chain applies cleanly on a
# fresh Postgres 16, is idempotent on re-run (strict
# mode), and the UEBA alembic chain round-trips
@@ -119,6 +122,50 @@ jobs:
docker compose up -d fusion
python3 scripts/integration/spine_test.py --await-alert --title "${TITLE}" --timeout 180
+ # ── Chaos: Postgres outage — graceful degradation + self-heal ────────
+ # Kill Postgres mid-stream. The fusion AlertSink must degrade to
+ # "fused alerts still flow over Kafka/WS, persistence is dropped for the
+ # outage window" WITHOUT crashing the consumer, and must self-heal once
+ # Postgres returns. Distinct event titles side-step fusion's in-memory
+ # dedup so the post-restart event is a fresh persist, not a duplicate.
+ # (The during-outage event's row is intentionally not recovered — a hard
+ # DB outage is a degradation window, not corruption; the healed event
+ # proves persistence resumes.)
+ - name: Chaos — Postgres outage (graceful degradation + self-heal)
+ run: |
+ set -euo pipefail
+ OUT="PgOutage-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-during"
+ HEAL="PgOutage-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-healed"
+
+ echo "── killing postgres ──"
+ docker compose kill postgres
+
+ # An event produced with the DB down must be accepted + processed
+ # (ingest and fusion do not depend on Postgres for the hot path).
+ python3 scripts/integration/spine_test.py --post-event --title "${OUT}"
+ sleep 8
+
+ # The consumer must still be running — a DB outage must not crash it.
+ fusion_cid="$(docker compose ps -q fusion)"
+ running="$(docker inspect -f '{{.State.Running}}' "${fusion_cid}")"
+ echo "fusion running during outage: ${running}"
+ [ "${running}" = "true" ] \
+ || { echo "::error::fusion crashed during the Postgres outage (fail-soft violated)"; exit 1; }
+
+ echo "── restoring postgres ──"
+ docker compose up -d postgres
+ for i in $(seq 1 30); do
+ if docker compose exec -T postgres pg_isready >/dev/null 2>&1; then
+ echo "postgres accepting connections after ${i}s"; break
+ fi
+ sleep 1
+ done
+
+ # A fresh event after restart must persist — proving the sink and the
+ # API both self-heal their Postgres pools with no restart.
+ python3 scripts/integration/spine_test.py --post-event --title "${HEAL}"
+ python3 scripts/integration/spine_test.py --await-alert --title "${HEAL}" --timeout 180
+
- name: Capture forensics on failure
if: failure()
run: |
@@ -127,6 +174,7 @@ jobs:
echo "── ingest ──"; docker compose logs --tail=100 --no-color ingest-worker || true
echo "── realtime ──"; docker compose logs --tail=100 --no-color realtime || true
echo "── api ──"; docker compose logs --tail=100 --no-color api || true
+ echo "── postgres ──"; docker compose logs --tail=60 --no-color postgres || true
echo "── kafka ──"; docker compose logs --tail=60 --no-color kafka || true
- name: Teardown
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b44ad82f..7db8bb93b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Phase 3.2 — Postgres-outage chaos gate (fail-soft + self-heal).** Extends the `integration.yml` spine job with a second chaos scenario beyond the consumer-kill test: kill Postgres mid-stream, assert the fusion consumer keeps running (the `AlertSink` degrades to "fused alerts still stream over Kafka/WS, persistence dropped for the outage window" instead of crashing the worker), then restart Postgres and assert a *fresh* event persists — proving the sink's asyncpg pool and the API's SQLAlchemy pool both self-heal with no service restart. Distinct event titles side-step fusion's in-memory dedup so the post-restart event is a genuine fresh persist. Verified locally against a real Postgres 16 before gating (persist during outage → `None` with no raise; first persist after restart → row written). `scripts/integration/spine_test.py` polling now swallows transient HTTP errors during the recovery window so a 5xx blip while the API reconnects extends the poll rather than failing the run.
- **Phase 3.1 — the event spine is now continuous, and CI proves it with real containers.** The reality audit found two silent gaps in the product's central claim: ingest published normalized OCSF events to `aisoc.raw_events` that nothing consumed, and fusion published to `aisoc.alerts.fused` that nothing persisted — a raw event could never become an alert row without a human calling the API. Both bridges now exist in `services/fusion`: a deterministic promotion policy (`app/services/promoter.py` — OCSF Findings-category events and `severity_id >= 4` telemetry become `RawAlert`s; everything else is left to the detection engine by design) and a fail-soft, idempotent Postgres `AlertSink` (`app/services/alert_sink.py` — dedup-fingerprint-guarded insert, duplicates never persisted, DB outage degrades instead of crashing the consumer). New `.github/workflows/integration.yml` gates three claims against real containers, no mocks: (1) **spine** — `POST /v1/ingest/batch` → OCSF normalize → Kafka → fusion → WebSocket `alert.fused` frame + Postgres row via `GET /api/v1/alerts`, plus duplicate suppression and a chaos step (kill the fusion consumer mid-stream, produce, restart, assert zero event loss) — driver: `scripts/integration/spine_test.py`; (2) **migrations** — the full SQL chain applies on fresh Postgres 16, re-run is a no-op (new `AISOC_MIGRATIONS_STRICT=1` mode fails CI on any failed migration), and the UEBA alembic chain round-trips upgrade → downgrade → upgrade; (3) **backup-restore** — `scripts/backup.sh`/`restore.sh` against Postgres + MinIO: seed → backup → destroy → restore → assert full integrity, with measured RTO published to the job summary. 20 new fusion unit tests cover the mapping/skip logic (`test_promoter.py`, `test_alert_sink.py`); full fusion suite 71/71.
### Fixed
diff --git a/scripts/integration/spine_test.py b/scripts/integration/spine_test.py
index da1e3244f..b5a2cd109 100644
--- a/scripts/integration/spine_test.py
+++ b/scripts/integration/spine_test.py
@@ -160,16 +160,23 @@ async def ws_listener(ticket: str, title: str, found: asyncio.Event) -> None:
async def await_alert_row(client: httpx.AsyncClient, title: str, timeout_s: int, repost: bool) -> None:
"""Poll the API until the alert row exists. Optionally re-POST the event to
- ride out consumer-group assignment races (dedup keeps this idempotent)."""
+ ride out consumer-group assignment races (dedup keeps this idempotent).
+
+ Transient HTTP errors are swallowed and retried rather than fatal: during
+ the Postgres-outage chaos step the API and fusion are mid-reconnect, so a
+ 5xx blip must extend the poll window, not fail the whole test."""
deadline = time.monotonic() + timeout_s
last_post = time.monotonic()
while time.monotonic() < deadline:
- if await count_alerts_titled(client, title) >= 1:
- log("alert row visible via GET /api/v1/alerts")
- return
- if repost and time.monotonic() - last_post > REPOST_INTERVAL_S:
- await post_event(client, title)
- last_post = time.monotonic()
+ try:
+ if await count_alerts_titled(client, title) >= 1:
+ log("alert row visible via GET /api/v1/alerts")
+ return
+ if repost and time.monotonic() - last_post > REPOST_INTERVAL_S:
+ await post_event(client, title)
+ last_post = time.monotonic()
+ except httpx.HTTPError as exc:
+ log(f"transient error while polling (will retry): {exc}")
await asyncio.sleep(3)
raise SystemExit(f"alert row for {title!r} never appeared within {timeout_s}s")