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-A1): populate the ClickHouse event lake from the raw-events stream (#446)

Beenu Arorac06283253b06
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a3d4b5b55..360d6b9ae 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -369,7 +369,9 @@ jobs:
# service boot, no Postgres/Kafka/Redis".
# asyncpg: required since Phase 3.1 — the fusion AlertSink persists
# fused alerts to the Postgres alert store.
- run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis fastapi httpx aiokafka asyncpg
+ # clickhouse-driver: required since Phase A1 — the fusion LakeWriter
+ # archives normalized events into the ClickHouse event lake.
+ run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis fastapi httpx aiokafka asyncpg clickhouse-driver
- name: Install pytest-cov (Phase 2.2 coverage gate)
run: pip install --quiet 'pytest-cov>=4,<7'
# Phase 2.2 — every wave-1 service now has a measured coverage
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 0e3bab306..88f3a5923 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -111,6 +111,28 @@ jobs:
- name: Run spine test
run: python3 scripts/integration/spine_test.py
+ # ── Phase A1: the ClickHouse event lake is actually populated ────────
+ # The spine test ingested events; assert they landed in the
+ # `aisoc.raw_events` lake (the writer flushes by size OR age, and the
+ # fusion worker runs a periodic-flush ticker so a low-traffic batch is
+ # never stranded). Queryability (count > 0), not exact-once, is the
+ # claim — MergeTree does not dedup and a Kafka replay may duplicate.
+ - name: Assert events landed in the ClickHouse lake
+ run: |
+ set -euo pipefail
+ ok=""
+ for i in $(seq 1 30); do
+ N="$(docker compose exec -T clickhouse clickhouse-client \
+ --user aisoc --password clickhouse_dev_secret \
+ --query 'SELECT count() FROM aisoc.raw_events' 2>/dev/null || echo 0)"
+ echo "lake row count (attempt ${i}): ${N}"
+ if [ "${N:-0}" -gt 0 ]; then ok=1; break; fi
+ sleep 2
+ done
+ [ -n "${ok}" ] \
+ || { echo "::error::ClickHouse lake was never populated from the raw-events stream"; \
+ docker compose logs --tail=80 --no-color fusion || true; exit 1; }
+
# ── Chaos: kill the fusion consumer, produce, restart, assert ────────
# The event is produced while the consumer is down; on restart the
# consumer group must resume from its committed offset and process it.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b9409ef61..f1d3ae076 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **Phase A1 — the ClickHouse event lake is now populated from the live stream.** The reality audit's central SIEM gap: the `aisoc.raw_events` lake table and its `/api/v1/lake/sql` read API existed with **no writer**, so every hunt/query ran against an empty warehouse. New `services/fusion/app/services/lake_writer.py` (`LakeWriter`) archives every normalized OCSF event from the `aisoc.raw_events` Kafka topic into ClickHouse — mapping the OCSF envelope to the lake columns (IPv4→IPv4-mapped-IPv6 coercion, `DateTime64` binding, MITRE/IOC extraction), batched by size **or** age, and **fail-soft** (a ClickHouse outage drops the batch and logs, never crashes the consumer). Archival is independent of promotion (a non-promoted Medium event is still queryable), and a background periodic-flush ticker guarantees a low-traffic batch is never stranded. Wired into the fusion consumer + lifespan; `docker-compose.yml` fusion service gets ClickHouse env + `depends_on`. `integration.yml` gains a Phase A1 gate asserting `SELECT count() FROM aisoc.raw_events > 0` after the spine ingests, against a live ClickHouse container (verified locally: a real INSERT round-trips). Claim-to-gate matrix adds a GATED row "Ingested events land in the queryable ClickHouse lake" (16 GATED / 11 PARTIAL / 1 NO GATE). At-least-once with a deterministic `event_id` (MergeTree does not dedup; the gate asserts queryability, not exact-once).
+
### Security
- **CodeQL (`security-and-quality`) alert cleanup.** Resolved the open code-scanning alerts surfaced by the fresh `security-and-quality` analysis. Real code fixes: (1) **`go/clear-text-logging` + `go/log-injection`** in `services/ingest/internal/enrichment/shodan.go` — the failure path logged the raw transport `err` (which can carry the request URL with the Shodan API key or response-derived data) alongside an unsanitized, attacker-influenceable `ip`; now it logs only a control-char-stripped IP (`sanitizeLogValue`) and never the error object. (2) **`py/stack-trace-exposure`** in `services/actions/app/api/router.py` — the action record echoed `str(exc)` back to the API caller; it now returns only the exception *type* and logs full detail server-side. (3) **`py/clear-text-storage-sensitive-data`** in `scripts/connector_conformance.py` — a false positive where the integer count of `secret`-type fields tripped CodeQL's sensitive-name heuristic; renamed the count to `vaulted` (accurate — those fields are vault-encrypted) so the matrix write is no longer misread as clear-text secret storage. (4) **`py/ineffectual-statement`** (×7) — Protocol/abstract method bodies written as bare `...` now use docstring bodies. (5) **`py/empty-except`** (×3) — silent `except: pass` blocks now carry an explanatory comment. The 20 `py/request-without-cert-validation` findings are the connector/appliance clients' TLS controls, which **default to `verify=True`** and only disable verification when an operator explicitly opts in (required for on-prem SIEM/firewall appliances with self-signed/internal-CA certs); these are triaged as accepted-risk (secure-by-default, explicit opt-in), with CA-bundle certificate pinning tracked as the recommended future alternative.
diff --git a/docker-compose.yml b/docker-compose.yml
index fe6a0de46..eb1d9098c 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -322,12 +322,20 @@ services:
condition: service_healthy
kafka:
condition: service_healthy
+ clickhouse:
+ condition: service_started
ports:
- "127.0.0.1:8003:8003"
environment:
KAFKA_BOOTSTRAP_SERVERS: kafka:29092
REDIS_URL: redis://:redis_dev_secret@redis:6379/3
DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc
+ # Phase A1 — populate the ClickHouse event lake from the raw-events stream.
+ CLICKHOUSE_HOST: clickhouse
+ CLICKHOUSE_PORT: "9000"
+ CLICKHOUSE_DATABASE: aisoc
+ CLICKHOUSE_USER: aisoc
+ CLICKHOUSE_PASSWORD: clickhouse_dev_secret
networks:
- aisoc
restart: unless-stopped
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 93fc3cfa0..b663e8242 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -35,12 +35,13 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Signed / attested release artifacts | (implied by "run next to crown jewels") | `release.yml` + `publish-images.yml` (cosign keyless signatures, CycloneDX SBOM attestation, BuildKit SLSA provenance + SPDX SBOM per image; SHA-pinned actions), `build-extensions.yml` (extension cosign) | GATED | - |
| Insecure defaults hard-fail in production | (implied by self-host) | `ci.yml` api tests (`test_security_defaults.py::test_enforce_*`; `enforce_secure_defaults` raises at boot in production) | GATED | - |
| OpenAPI stability for 3 SDKs + MCP | (implied by SDKs) | `check-openapi.yml` (drift) + `openapi-breaking.yml` (`scripts/openapi_diff.py` — PR spec vs base fails on removed endpoint/schema/field, type change, tightened request, or dropped enum value) | GATED | - |
+| Ingested events land in the queryable ClickHouse lake | README (SIEM / lake) | `integration.yml :: spine` (Phase A1 — after the spine ingests, asserts `SELECT count() FROM aisoc.raw_events > 0` against the live ClickHouse container; `services/fusion` `LakeWriter` archives every normalized event) | GATED | - |
## Summary
-- GATED: 15
+- GATED: 16
- PARTIAL: 11
-- NO GATE: 1 (Phase 2 moved insecure-defaults-hard-fail to GATED and secret/IaC/container scanning to PARTIAL; the Phase 2 continuation moved signed/attested releases to GATED; Phase 3.4 moved cross-store isolation to GATED; Phase 4 moved the DAC candidate-rule gate and imported-count honesty gate to GATED; Phase 10 moved connector "live Test connection" off NO GATE; Phase 11 moved OpenAPI breaking-change semantics to GATED. The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c, which needs a budgeted live-agent run)
+- NO GATE: 1 (Phase 2 moved insecure-defaults-hard-fail to GATED and secret/IaC/container scanning to PARTIAL; the Phase 2 continuation moved signed/attested releases to GATED; Phase 3.4 moved cross-store isolation to GATED; Phase 4 moved the DAC candidate-rule gate and imported-count honesty gate to GATED; Phase 10 moved connector "live Test connection" off NO GATE; Phase 11 moved OpenAPI breaking-change semantics to GATED; Phase A1 gated the ClickHouse lake being populated. The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c, which needs a budgeted live-agent run)
The ratchet is enforced by `scripts/check_claim_gate_matrix.py` (wired into `security.yml`): the NO GATE count may only decrease.
diff --git a/services/fusion/Dockerfile b/services/fusion/Dockerfile
index a3b399f7e..1a357951b 100644
--- a/services/fusion/Dockerfile
+++ b/services/fusion/Dockerfile
@@ -37,7 +37,8 @@ RUN set -eux; \
"simhash>=2.1.2,<3" \
"scikit-learn>=1.4,<2" \
"lightgbm>=4.3,<5" \
- "numpy>=1.26,<2" ; \
+ "numpy>=1.26,<2" \
+ "clickhouse-driver>=0.2.6,<0.3" ; \
fi
COPY app/ ./app/
diff --git a/services/fusion/app/core/config.py b/services/fusion/app/core/config.py
index 6218a79d2..7e93d45a1 100644
--- a/services/fusion/app/core/config.py
+++ b/services/fusion/app/core/config.py
@@ -29,6 +29,19 @@ class Settings(BaseSettings):
# Postgres alert store (app/services/alert_sink.py). Fail-soft by design.
alert_sink_enabled: bool = Field(default=True, alias="AISOC_ALERT_SINK_ENABLED")
+ # Phase A1 — archive every normalized OCSF event into the ClickHouse event
+ # lake (app/services/lake_writer.py). Independent of promotion: an event
+ # that isn't promoted to an alert must still be queryable via /lake/sql.
+ # Fail-soft; disables itself if clickhouse-driver / the server is absent.
+ lake_writer_enabled: bool = Field(default=True, alias="AISOC_LAKE_WRITER_ENABLED")
+ clickhouse_host: str = Field(default="localhost", alias="CLICKHOUSE_HOST")
+ clickhouse_port: int = Field(default=9000, alias="CLICKHOUSE_PORT")
+ clickhouse_database: str = Field(default="aisoc", alias="CLICKHOUSE_DATABASE")
+ clickhouse_user: str = Field(default="default", alias="CLICKHOUSE_USER")
+ clickhouse_password: str = Field(default="", alias="CLICKHOUSE_PASSWORD")
+ lake_batch_size: int = Field(default=100, alias="AISOC_LAKE_BATCH_SIZE")
+ lake_batch_max_age_seconds: float = Field(default=2.0, alias="AISOC_LAKE_BATCH_MAX_AGE_SECONDS")
+
# Redis
redis_url: str = Field(default="redis://localhost:6379/2", alias="REDIS_URL")
dedup_window_seconds: int = Field(default=300, alias="DEDUP_WINDOW_SECONDS")
diff --git a/services/fusion/app/main.py b/services/fusion/app/main.py
index 5f3d05e99..e197cc249 100644
--- a/services/fusion/app/main.py
+++ b/services/fusion/app/main.py
@@ -14,6 +14,7 @@ from app.services.correlator import Correlator
from app.services.deduplicator import Deduplicator
from app.services.entity_risk import EntityRiskEngine
from app.services.fusion_engine import FusionEngine
+from app.services.lake_writer import LakeWriter
from app.workers.consumer import FusionWorker
@@ -38,7 +39,21 @@ async def lifespan(app: FastAPI):
# is continuous (raw event → alert row). Fail-soft: a missing/unreachable
# DB never blocks the Kafka pipeline.
sink = AlertSink(settings.database_url) if settings.alert_sink_enabled else None
- worker = FusionWorker(engine, sink=sink)
+ # Phase A1 — populate the ClickHouse event lake from the raw-events stream.
+ lake = (
+ LakeWriter(
+ host=settings.clickhouse_host,
+ port=settings.clickhouse_port,
+ database=settings.clickhouse_database,
+ user=settings.clickhouse_user,
+ password=settings.clickhouse_password,
+ batch_size=settings.lake_batch_size,
+ batch_max_age_seconds=settings.lake_batch_max_age_seconds,
+ )
+ if settings.lake_writer_enabled
+ else None
+ )
+ worker = FusionWorker(engine, sink=sink, lake=lake)
set_worker(worker)
# Start Kafka worker as a background task
diff --git a/services/fusion/app/services/lake_writer.py b/services/fusion/app/services/lake_writer.py
new file mode 100644
index 000000000..030357c66
--- /dev/null
+++ b/services/fusion/app/services/lake_writer.py
@@ -0,0 +1,364 @@
+"""Write normalized OCSF events into the ClickHouse event lake (Phase A1).
+
+The reality audit found the central SIEM gap: ingest publishes normalized OCSF
+events to Kafka and fusion promotes a subset into Postgres alerts, but
+**nothing populated the ClickHouse ``aisoc.raw_events`` lake** — the table and
+its read API (``/api/v1/lake/sql``) existed with no writer, so every hunt/query
+ran against an empty warehouse.
+
+This module closes that gap. Fusion already deserializes every ``aisoc.raw_events``
+Kafka message (for promotion), so it is the natural place to also archive each
+event into the lake. Archival is independent of the promotion decision: a
+Medium-severity event that is (correctly) not promoted to an alert must still be
+queryable in the lake.
+
+Design constraints (mirroring ``AlertSink``):
+
+* **Fail-soft.** A ClickHouse outage must degrade to "events still flow through
+ Kafka/fusion, lake archival is dropped for the outage window" — never crash
+ the consumer. A failed flush drops that batch (best-effort archival) rather
+ than growing an unbounded in-memory buffer.
+* **Batched.** ClickHouse is happiest with bulk inserts, so events are buffered
+ and flushed by size (``batch_size``) or age (``batch_max_age_seconds``); the
+ consumer calls :meth:`flush_if_stale` each loop and :meth:`flush` on stop.
+* **At-least-once with a deterministic ``event_id``.** MergeTree does not
+ deduplicate, so a Kafka replay can produce a duplicate lake row. Each row
+ carries the ingest event id (when it is a valid UUID) so downstream queries
+ can ``argMax``/``LIMIT 1 BY event_id`` if exact-once is required. The Phase A1
+ gate asserts *queryability* (``count >= 1``), not exact-once.
+
+``clickhouse-driver`` is synchronous, so every insert is dispatched to a worker
+thread via :func:`asyncio.to_thread` to keep the fusion event loop responsive.
+If the driver is not installed (some dev images), the writer disables itself at
+construction and logs once, rather than failing fusion import.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import ipaddress
+import json
+import time
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger()
+
+# Column order for the INSERT — must match ``_row`` and the ClickHouse schema in
+# ``services/api/clickhouse/001_init.sql``.
+_COLUMNS = (
+ "event_id",
+ "tenant_id",
+ "event_time",
+ "class_uid",
+ "category_uid",
+ "severity_id",
+ "severity",
+ "activity_id",
+ "source_ip",
+ "dest_ip",
+ "src_port",
+ "dst_port",
+ "protocol",
+ "src_hostname",
+ "dst_hostname",
+ "user_name",
+ "process_name",
+ "file_path",
+ "hash_sha256",
+ "connector_type",
+ "raw_payload",
+ "ocsf_json",
+ "mitre_techniques",
+ "mitre_tactics",
+ "iocs",
+)
+
+_INSERT_SQL = f"INSERT INTO aisoc.raw_events ({', '.join(_COLUMNS)}) VALUES"
+
+# ClickHouse IPv6 columns reject empty/invalid strings; "::" is the safe null.
+_NULL_IP = "::"
+
+
+def _get(obj: Any, *path: str) -> Any:
+ cur: Any = obj
+ for key in path:
+ if not isinstance(cur, dict):
+ return None
+ cur = cur.get(key)
+ return cur
+
+
+def _as_int(value: Any, default: int = 0) -> int:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
+
+
+def _as_str(value: Any) -> str:
+ return value if isinstance(value, str) else ("" if value is None else str(value))
+
+
+def _as_ip(value: Any) -> str:
+ """Normalise to a valid IP string; '::' when absent/invalid.
+
+ Kept as a string in the row dict (readable, serialisable); converted to an
+ ``ipaddress`` object only at insert time by :func:`_to_ip_obj`.
+ """
+ if not isinstance(value, str) or not value.strip():
+ return _NULL_IP
+ candidate = value.strip()
+ try:
+ ipaddress.ip_address(candidate)
+ return candidate
+ except ValueError:
+ return _NULL_IP
+
+
+def _to_ip_obj(value: str) -> ipaddress.IPv6Address:
+ """Bind an IPv6-typed ClickHouse column.
+
+ The column is ``IPv6``, so an IPv4 address must be mapped to its
+ IPv4-mapped IPv6 form (``::ffff:a.b.c.d``); the driver rejects a bare
+ ``IPv4Address``. Invalid input -> the null IPv6 ``::``.
+ """
+ try:
+ addr = ipaddress.ip_address(value)
+ except ValueError:
+ return ipaddress.IPv6Address(_NULL_IP)
+ if isinstance(addr, ipaddress.IPv4Address):
+ return ipaddress.IPv6Address("::ffff:" + str(addr))
+ return addr
+
+
+def _tenant_uuid(message: dict[str, Any], ocsf: dict[str, Any]) -> str | None:
+ raw = message.get("tenant_id") or ocsf.get("tenant_uid")
+ try:
+ return str(uuid.UUID(str(raw)))
+ except (TypeError, ValueError):
+ return None
+
+
+def _event_time(ocsf: dict[str, Any]) -> datetime:
+ """Return a naive-UTC ``datetime`` for the ClickHouse DateTime64 column.
+
+ clickhouse-driver maps a Python ``datetime`` (not a string) onto DateTime64;
+ a bad/absent timestamp falls back to now().
+ """
+ raw = ocsf.get("time")
+ if isinstance(raw, str) and raw.strip():
+ try:
+ dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ return dt.astimezone(UTC).replace(tzinfo=None)
+ except ValueError:
+ pass
+ return datetime.now(UTC).replace(tzinfo=None)
+
+
+def _first_hash(ocsf: dict[str, Any]) -> str:
+ fps = _get(ocsf, "file", "fingerprints")
+ if isinstance(fps, list) and fps and isinstance(fps[0], dict):
+ return _as_str(fps[0].get("value"))
+ return _as_str(ocsf.get("hash_sha256"))
+
+
+def _mitre(ocsf: dict[str, Any]) -> tuple[list[str], list[str]]:
+ techniques: list[str] = []
+ tactics: list[str] = []
+ block = ocsf.get("mitre_attck")
+ if isinstance(block, list):
+ for entry in block:
+ if not isinstance(entry, dict):
+ continue
+ tid = entry.get("technique_id")
+ if isinstance(tid, str) and tid and tid not in techniques:
+ techniques.append(tid)
+ for name in entry.get("tactic_names") or []:
+ if isinstance(name, str) and name and name not in tactics:
+ tactics.append(name)
+ return techniques, tactics
+
+
+def _iocs(ocsf: dict[str, Any]) -> list[str]:
+ out: list[str] = []
+ for value in (
+ _get(ocsf, "src_endpoint", "ip"),
+ _get(ocsf, "dst_endpoint", "ip"),
+ _first_hash(ocsf),
+ ):
+ if isinstance(value, str) and value.strip():
+ out.append(value.strip())
+ return out
+
+
+def event_to_row(message: dict[str, Any]) -> dict[str, Any] | None:
+ """Map an ingest NormalizedEvent envelope to a ClickHouse row dict.
+
+ Returns ``None`` when the message has no OCSF body or no UUID tenant — such
+ messages are handled (dead-lettered) elsewhere and must not reach the lake.
+ """
+ ocsf = message.get("ocsf_event")
+ if not isinstance(ocsf, dict):
+ return None
+ tenant = _tenant_uuid(message, ocsf)
+ if tenant is None:
+ return None
+
+ techniques, tactics = _mitre(ocsf)
+ connector_type = _as_str(_get(ocsf, "metadata", "product", "name")) or _as_str(message.get("connector_type"))
+
+ row: dict[str, Any] = {
+ "tenant_id": tenant,
+ "event_time": _event_time(ocsf),
+ "class_uid": _as_int(ocsf.get("class_uid")),
+ "category_uid": _as_int(ocsf.get("category_uid")),
+ "severity_id": _as_int(ocsf.get("severity_id")),
+ "severity": _as_str(ocsf.get("severity")),
+ "activity_id": _as_int(ocsf.get("activity_id")),
+ "source_ip": _as_ip(_get(ocsf, "src_endpoint", "ip")),
+ "dest_ip": _as_ip(_get(ocsf, "dst_endpoint", "ip")),
+ "src_port": _as_int(_get(ocsf, "src_endpoint", "port")),
+ "dst_port": _as_int(_get(ocsf, "dst_endpoint", "port")),
+ "protocol": _as_str(ocsf.get("protocol") or _get(ocsf, "connection_info", "protocol_name")),
+ "src_hostname": _as_str(_get(ocsf, "device", "name") or _get(ocsf, "src_endpoint", "hostname")),
+ "dst_hostname": _as_str(_get(ocsf, "dst_endpoint", "hostname")),
+ "user_name": _as_str(_get(ocsf, "actor", "user", "name")),
+ "process_name": _as_str(_get(ocsf, "process", "name")),
+ "file_path": _as_str(_get(ocsf, "file", "path")),
+ "hash_sha256": _first_hash(ocsf),
+ "connector_type": connector_type,
+ "raw_payload": _as_str(ocsf.get("raw_data"))[:65536],
+ "ocsf_json": json.dumps(ocsf, default=str)[:262144],
+ "mitre_techniques": techniques,
+ "mitre_tactics": tactics,
+ "iocs": _iocs(ocsf),
+ }
+
+ # Only set a deterministic event_id when the ingest id is a real UUID;
+ # otherwise let ClickHouse default generateUUIDv4().
+ raw_id = message.get("id") or message.get("event_id")
+ try:
+ row["event_id"] = str(uuid.UUID(str(raw_id)))
+ except (TypeError, ValueError):
+ row["event_id"] = None
+ return row
+
+
+class LakeWriter:
+ """Batched, fail-soft ClickHouse writer for the ``aisoc.raw_events`` lake."""
+
+ def __init__(
+ self,
+ *,
+ host: str,
+ port: int = 9000,
+ database: str = "aisoc",
+ user: str = "default",
+ password: str = "",
+ batch_size: int = 100,
+ batch_max_age_seconds: float = 2.0,
+ ) -> None:
+ self._host = host
+ self._port = port
+ self._database = database
+ self._user = user
+ self._password = password
+ self._batch_size = max(1, batch_size)
+ self._batch_max_age = batch_max_age_seconds
+ self._client: Any | None = None
+ self._buffer: list[dict[str, Any]] = []
+ self._buffer_started_at: float = 0.0
+ self._disabled = False
+ self.rows_written = 0
+ self.flush_failures = 0
+
+ async def start(self) -> None:
+ if self._disabled:
+ return
+ try:
+ from clickhouse_driver import Client # noqa: PLC0415
+
+ self._client = Client(
+ host=self._host,
+ port=self._port,
+ database=self._database,
+ user=self._user,
+ password=self._password or "",
+ connect_timeout=10,
+ )
+ logger.info("lake_writer.started", host=self._host, database=self._database)
+ except ImportError:
+ self._disabled = True
+ logger.warning("lake_writer.disabled_no_driver")
+ except Exception as exc: # noqa: BLE001 — degrade, never crash the worker
+ self._disabled = True
+ logger.error("lake_writer.connect_failed", error=str(exc))
+
+ async def stop(self) -> None:
+ await self.flush()
+ if self._client is not None:
+ try:
+ await asyncio.to_thread(self._client.disconnect)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("lake_writer.disconnect_failed", error=str(exc))
+ self._client = None
+
+ async def write_event(self, message: dict[str, Any]) -> bool:
+ """Buffer one normalized event for the lake. Returns True if buffered.
+
+ Flushes automatically when the buffer reaches ``batch_size``.
+ """
+ if self._disabled:
+ return False
+ row = event_to_row(message)
+ if row is None:
+ return False
+ if not self._buffer:
+ self._buffer_started_at = time.monotonic()
+ self._buffer.append(row)
+ if len(self._buffer) >= self._batch_size:
+ await self.flush()
+ return True
+
+ async def flush_if_stale(self) -> None:
+ if self._buffer and (time.monotonic() - self._buffer_started_at) >= self._batch_max_age:
+ await self.flush()
+
+ async def flush(self) -> None:
+ if self._disabled or not self._buffer:
+ return
+ batch = self._buffer
+ self._buffer = []
+ client = self._client
+ if client is None:
+ return
+
+ def _insert() -> None:
+ # clickhouse-driver executes INSERT ... VALUES with a list of dicts.
+ # Coerce the typed columns (IPv6) to the objects the driver binds,
+ # and omit event_id when None so the column DEFAULT applies.
+ rows: list[dict[str, Any]] = []
+ for row in batch:
+ out = {k: v for k, v in row.items() if not (k == "event_id" and v is None)}
+ out["source_ip"] = _to_ip_obj(row["source_ip"])
+ out["dest_ip"] = _to_ip_obj(row["dest_ip"])
+ rows.append(out)
+ client.execute(_INSERT_SQL, rows, types_check=True)
+
+ try:
+ await asyncio.to_thread(_insert)
+ self.rows_written += len(batch)
+ except Exception as exc: # noqa: BLE001 — best-effort archival; drop the batch
+ self.flush_failures += 1
+ logger.error("lake_writer.flush_failed", error=str(exc), dropped=len(batch))
+
+ def metrics(self) -> dict[str, int]:
+ return {
+ "rows_written": self.rows_written,
+ "flush_failures": self.flush_failures,
+ "buffered": len(self._buffer),
+ }
diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.py
index 77860fd6c..b7f45a1ff 100644
--- a/services/fusion/app/workers/consumer.py
+++ b/services/fusion/app/workers/consumer.py
@@ -4,6 +4,8 @@ normalized OCSF events), runs them through the fusion engine, publishes fused
results back to Kafka, and persists non-duplicate alerts to Postgres.
"""
+import asyncio
+import contextlib
import json
import structlog
@@ -15,6 +17,7 @@ from app.services.alert_sink import AlertSink
from app.services.dlq import DeadLetter, DeadLetterQueue, LoggingDLQ, safe_record
from app.services.event_schema import validate_event
from app.services.fusion_engine import FusionEngine
+from app.services.lake_writer import LakeWriter
from app.services.promoter import promote_normalized_event
logger = structlog.get_logger()
@@ -27,6 +30,7 @@ _METRICS = {
"promoted": 0,
"not_promoted": 0,
"persisted": 0,
+ "laked": 0,
"dead_lettered": 0,
"errors": 0,
}
@@ -40,15 +44,18 @@ class FusionWorker:
engine: FusionEngine,
sink: AlertSink | None = None,
dlq: DeadLetterQueue | None = None,
+ lake: LakeWriter | None = None,
) -> None:
self._engine = engine
self._sink = sink
+ self._lake = lake
# A poison message must never vanish silently; default to a structured
# logging DLQ so persistence-free deployments still get the signal.
self._dlq: DeadLetterQueue = dlq or LoggingDLQ()
self._consumer: AIOKafkaConsumer | None = None
self._producer: AIOKafkaProducer | None = None
self._running = False
+ self._flush_task: asyncio.Task | None = None
@property
def engine(self) -> FusionEngine:
@@ -56,7 +63,9 @@ class FusionWorker:
async def start(self) -> None:
topics = [settings.kafka_topic_alerts_raw]
- if settings.event_promotion_enabled:
+ # Subscribe to raw_events when EITHER promotion or lake archival needs
+ # it — the lake must fill even if promotion is turned off.
+ if settings.event_promotion_enabled or self._lake is not None:
topics.append(settings.kafka_topic_raw_events)
self._consumer = AIOKafkaConsumer(
*topics,
@@ -74,6 +83,12 @@ class FusionWorker:
await self._producer.start()
if self._sink is not None:
await self._sink.start()
+ if self._lake is not None:
+ await self._lake.start()
+ # Low-traffic safety net: a single buffered event would otherwise
+ # wait for the NEXT message before flush_if_stale runs. A background
+ # ticker guarantees the lake batch flushes by age even when idle.
+ self._flush_task = asyncio.create_task(self._periodic_flush())
self._running = True
logger.info(
"Fusion worker started",
@@ -81,17 +96,35 @@ class FusionWorker:
input_topics=topics,
output_topic=settings.kafka_topic_alerts_fused,
alert_sink=self._sink is not None,
+ lake_writer=self._lake is not None,
)
await self._consume_loop()
+ async def _periodic_flush(self) -> None:
+ interval = max(0.5, settings.lake_batch_max_age_seconds)
+ try:
+ while self._running:
+ await asyncio.sleep(interval)
+ if self._lake is not None:
+ await self._lake.flush_if_stale()
+ except asyncio.CancelledError: # pragma: no cover — shutdown path
+ pass
+
async def stop(self) -> None:
self._running = False
+ if self._flush_task is not None:
+ self._flush_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await self._flush_task
+ self._flush_task = None
if self._consumer:
await self._consumer.stop()
if self._producer:
await self._producer.stop()
if self._sink is not None:
await self._sink.stop()
+ if self._lake is not None:
+ await self._lake.stop()
logger.info("Fusion worker stopped", metrics=_METRICS)
async def _consume_loop(self) -> None:
@@ -103,6 +136,10 @@ class FusionWorker:
except Exception as exc:
_METRICS["errors"] += 1
logger.error("Failed to process message", error=str(exc), exc_info=True)
+ # Flush any stale lake batch so archival isn't stranded during a
+ # low-traffic window (batch fills by size OR age).
+ if self._lake is not None:
+ await self._lake.flush_if_stale()
async def _dead_letter(
self,
@@ -152,6 +189,12 @@ class FusionWorker:
return
if topic == settings.kafka_topic_raw_events:
+ # Phase A1 — archive EVERY normalized event into the ClickHouse lake
+ # first, independent of the promotion decision below. A non-promoted
+ # Medium event still has to be queryable via /lake/sql.
+ if self._lake is not None and await self._lake.write_event(payload):
+ _METRICS["laked"] += 1
+
# Ingest-normalized OCSF event — run the deterministic promotion
# policy (see app/services/promoter.py). Non-promoted events are
# dropped here by design; the detect stage owns rule evaluation.
diff --git a/services/fusion/pyproject.toml b/services/fusion/pyproject.toml
index 31257e96f..27b522820 100644
--- a/services/fusion/pyproject.toml
+++ b/services/fusion/pyproject.toml
@@ -25,6 +25,7 @@ simhash = "^2.1.2"
scikit-learn = "^1.4.0"
lightgbm = "^4.3.0"
numpy = "^1.26.0"
+clickhouse-driver = "^0.2.6"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.0"
diff --git a/services/fusion/tests/test_lake_writer.py b/services/fusion/tests/test_lake_writer.py
new file mode 100644
index 000000000..4a9d77296
--- /dev/null
+++ b/services/fusion/tests/test_lake_writer.py
@@ -0,0 +1,160 @@
+"""Phase A1 — ClickHouse lake writer tests.
+
+Proves the OCSF->column mapping, batching (size + age + stop flush), IP/UUID
+coercion, and the fail-soft contract (a ClickHouse error drops the batch and
+never raises into the consumer). Uses a fake client so no live ClickHouse is
+needed; the live-container assertion is the integration.yml gate.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.services.lake_writer import LakeWriter, event_to_row
+
+pytestmark = pytest.mark.asyncio
+
+TENANT = "11111111-1111-1111-1111-111111111111"
+
+
+def _message(**ocsf_overrides) -> dict:
+ ocsf = {
+ "class_uid": 2001,
+ "category_uid": 2,
+ "severity_id": 5,
+ "severity": "Critical",
+ "time": "2026-07-12T08:00:00Z",
+ "metadata": {"product": {"name": "Falcon", "vendor_name": "CrowdStrike"}},
+ "device": {"name": "WIN-DC01"},
+ "actor": {"user": {"name": "svc-backup"}},
+ "src_endpoint": {"ip": "10.20.30.40", "port": 51515},
+ "dst_endpoint": {"ip": "203.0.113.9", "port": 443},
+ "file": {"fingerprints": [{"value": "a" * 64}], "path": "/tmp/x"},
+ "mitre_attck": [{"technique_id": "T1003", "tactic_names": ["Credential Access"]}],
+ "raw_data": "raw log line",
+ }
+ ocsf.update(ocsf_overrides)
+ return {"id": "22222222-2222-2222-2222-222222222222", "tenant_id": TENANT, "ocsf_event": ocsf}
+
+
+class _FakeClient:
+ def __init__(self) -> None:
+ self.inserted: list[dict] = []
+ self.fail = False
+
+ def execute(self, sql, rows=None, **kwargs): # noqa: ANN001
+ if self.fail:
+ raise RuntimeError("clickhouse down")
+ if rows:
+ self.inserted.extend(rows)
+ return []
+
+ def disconnect(self): # noqa: D401
+ pass
+
+
+def _writer_with_fake(**kw) -> tuple[LakeWriter, _FakeClient]:
+ w = LakeWriter(host="x", **kw)
+ fake = _FakeClient()
+ w._client = fake # noqa: SLF001 — inject fake, skip start()
+ return w, fake
+
+
+# ── Mapping ──────────────────────────────────────────────────────────────────
+
+
+async def test_event_to_row_maps_core_fields():
+ row = event_to_row(_message())
+ assert row is not None
+ assert row["tenant_id"] == TENANT
+ assert row["class_uid"] == 2001
+ assert row["severity_id"] == 5
+ assert row["source_ip"] == "10.20.30.40"
+ assert row["dest_ip"] == "203.0.113.9"
+ assert row["user_name"] == "svc-backup"
+ assert row["src_hostname"] == "WIN-DC01"
+ assert row["hash_sha256"] == "a" * 64
+ assert row["connector_type"] == "Falcon"
+ assert row["mitre_techniques"] == ["T1003"]
+ assert row["mitre_tactics"] == ["Credential Access"]
+ assert row["event_id"] == "22222222-2222-2222-2222-222222222222"
+ assert "10.20.30.40" in row["iocs"]
+
+
+async def test_missing_ip_coerced_to_null_ipv6():
+ row = event_to_row(_message(src_endpoint={}, dst_endpoint={}))
+ assert row["source_ip"] == "::"
+ assert row["dest_ip"] == "::"
+
+
+async def test_non_uuid_event_id_left_none_for_default():
+ msg = _message()
+ msg["id"] = "not-a-uuid"
+ row = event_to_row(msg)
+ assert row["event_id"] is None
+
+
+async def test_no_ocsf_or_bad_tenant_returns_none():
+ assert event_to_row({"tenant_id": TENANT}) is None
+ assert event_to_row({"tenant_id": "nope", "ocsf_event": {"class_uid": 1}}) is None
+
+
+# ── Batching + flush ─────────────────────────────────────────────────────────
+
+
+async def test_flushes_when_batch_full():
+ w, fake = _writer_with_fake(batch_size=3)
+ for _ in range(3):
+ await w.write_event(_message())
+ assert len(fake.inserted) == 3
+ assert w.rows_written == 3
+ assert w.metrics()["buffered"] == 0
+
+
+async def test_buffers_until_full():
+ w, fake = _writer_with_fake(batch_size=5)
+ await w.write_event(_message())
+ await w.write_event(_message())
+ assert fake.inserted == [] # not yet flushed
+ assert w.metrics()["buffered"] == 2
+
+
+async def test_stop_flushes_remaining():
+ w, fake = _writer_with_fake(batch_size=100)
+ await w.write_event(_message())
+ await w.stop()
+ assert len(fake.inserted) == 1
+
+
+async def test_flush_if_stale_flushes_old_buffer():
+ w, fake = _writer_with_fake(batch_size=100, batch_max_age_seconds=0.0)
+ await w.write_event(_message())
+ await w.flush_if_stale()
+ assert len(fake.inserted) == 1
+
+
+async def test_omits_none_event_id_from_insert_row():
+ w, fake = _writer_with_fake(batch_size=1)
+ msg = _message()
+ msg["id"] = "not-a-uuid"
+ await w.write_event(msg)
+ assert "event_id" not in fake.inserted[0]
+
+
+# ── Fail-soft ────────────────────────────────────────────────────────────────
+
+
+async def test_flush_failure_drops_batch_and_does_not_raise():
+ w, fake = _writer_with_fake(batch_size=2)
+ fake.fail = True
+ await w.write_event(_message())
+ await w.write_event(_message()) # triggers flush -> fails
+ assert w.flush_failures == 1
+ assert w.rows_written == 0
+ assert w.metrics()["buffered"] == 0 # batch was dropped, not re-buffered
+
+
+async def test_disabled_writer_is_noop():
+ w = LakeWriter(host="x")
+ w._disabled = True # noqa: SLF001
+ assert await w.write_event(_message()) is False
+ await w.flush() # no raise