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.

perf(agents): concurrent triage, with ordering kept per entity (parity 6.9)

Beenu Arorac1e4d1223b51
diff --git a/services/agents/app/workers/entity_lane.py b/services/agents/app/workers/entity_lane.py
new file mode 100644
index 000000000..d52db1390
--- /dev/null
+++ b/services/agents/app/workers/entity_lane.py
@@ -0,0 +1,185 @@
+"""Concurrency for triage, with ordering kept per entity (parity 6.9).
+
+Auto-triage processed one alert at a time: `async for msg` with an
+inline `await` on an LLM call. That is an I/O-bound stage serialised on
+network latency, and it is the slowest thing in the pipeline by a wide
+margin — a replica spends almost all of its time waiting rather than
+working.
+
+Why not simply run them all at once
+-----------------------------------
+Because the ordering matters for exactly the alerts that are related.
+Two alerts about one host are the ones most likely to be the same
+incident, and triage reads institutional memory written by earlier
+triages of the same entity. Running them concurrently makes the second
+one's context depend on whether the first happened to finish first,
+which turns a deterministic verdict into a race.
+
+So concurrency is **per entity**: alerts about different entities run in
+parallel up to a bound, and alerts about one entity run in the order
+they arrived. That is the same property partitioning the Kafka topic by
+entity gives across replicas, applied inside one.
+
+Why a bound at all
+------------------
+An unbounded fan-out hands the model provider as many concurrent
+requests as the topic can deliver, which is how a burst becomes a rate
+limit and then a retry storm. The default is small and deliberately
+stated as a policy choice rather than a measurement.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+from collections.abc import Awaitable, Callable
+
+import structlog
+
+logger = structlog.get_logger()
+
+#: How many entities may be in flight at once. A policy choice, not a
+#: measurement: nothing here claims eight is optimal. It is small enough
+#: that a burst does not become a provider rate limit and large enough
+#: that a replica is not idling on one network round trip.
+DEFAULT_MAX_CONCURRENCY = 8
+
+#: An upper bound on what an operator may ask for, for the same reason.
+MAX_CONCURRENCY_CEILING = 64
+
+_CONCURRENCY_ENV = "AISOC_TRIAGE_CONCURRENCY"
+
+
+def configured_concurrency() -> int:
+ """How many entities to process at once, from the environment.
+
+ An unreadable or out-of-range value falls back to the default and
+ says so. Silently clamping a typo would leave an operator who asked
+ for 200 believing they got it.
+ """
+ raw = os.environ.get(_CONCURRENCY_ENV, "").strip()
+ if not raw:
+ return DEFAULT_MAX_CONCURRENCY
+ try:
+ value = int(raw)
+ except ValueError:
+ logger.error("triage.bad_concurrency", value=raw, using=DEFAULT_MAX_CONCURRENCY)
+ return DEFAULT_MAX_CONCURRENCY
+ if value < 1 or value > MAX_CONCURRENCY_CEILING:
+ logger.error(
+ "triage.concurrency_out_of_range",
+ value=value,
+ ceiling=MAX_CONCURRENCY_CEILING,
+ using=DEFAULT_MAX_CONCURRENCY,
+ )
+ return DEFAULT_MAX_CONCURRENCY
+ return value
+
+
+def entity_of(alert: dict) -> str:
+ """The entity an alert is about, in fusion's own precedence.
+
+ The same order ``RawAlert.correlation_key()`` uses and the same order
+ the ingest partition key uses, so the lane an alert runs in and the
+ incident it correlates into are named by one field. An alert naming
+ nobody gets its own lane, keyed by id: it shares an incident with
+ nothing, so there is no order to preserve.
+ """
+ for key in ("src_ip", "hostname", "host", "username", "user", "domain"):
+ value = alert.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ entities = alert.get("entities")
+ if isinstance(entities, list):
+ for item in entities:
+ if isinstance(item, dict):
+ value = item.get("value")
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ identifier = alert.get("id") or alert.get("alert_id")
+ return f"alert:{identifier}" if identifier else "unknown"
+
+
+class EntityLanes:
+ """Runs work concurrently across entities and serially within one.
+
+ Not a queue per entity held forever: a lane is created on demand and
+ dropped when it drains, so a long-running deployment does not
+ accumulate one lock per host it has ever seen.
+ """
+
+ def __init__(self, max_concurrency: int | None = None) -> None:
+ self._limit = max_concurrency if max_concurrency is not None else configured_concurrency()
+ self._semaphore = asyncio.Semaphore(self._limit)
+ self._locks: dict[str, asyncio.Lock] = {}
+ self._waiters: dict[str, int] = {}
+ self._tasks: set[asyncio.Task] = set()
+
+ @property
+ def limit(self) -> int:
+ return self._limit
+
+ @property
+ def in_flight(self) -> int:
+ return len(self._tasks)
+
+ @property
+ def tracked_entities(self) -> int:
+ """Lanes currently held. Should return to zero when idle."""
+ return len(self._locks)
+
+ def _lock_for(self, entity: str) -> asyncio.Lock:
+ lock = self._locks.get(entity)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._locks[entity] = lock
+ self._waiters[entity] = self._waiters.get(entity, 0) + 1
+ return lock
+
+ def _release(self, entity: str) -> None:
+ remaining = self._waiters.get(entity, 1) - 1
+ if remaining <= 0:
+ self._waiters.pop(entity, None)
+ self._locks.pop(entity, None)
+ else:
+ self._waiters[entity] = remaining
+
+ async def submit(self, entity: str, work: Callable[[], Awaitable[None]]) -> asyncio.Task:
+ """Schedule ``work`` in ``entity``'s lane and return its task.
+
+ Returns immediately once the task is created; the caller decides
+ when to wait. The task never raises: an exception escaping a
+ background task leaves nothing in any log, which is the defect
+ the consume loop's own guard exists for.
+ """
+ lock = self._lock_for(entity)
+
+ async def _run() -> None:
+ try:
+ async with self._semaphore, lock:
+ await work()
+ except Exception as exc: # noqa: BLE001 — see the docstring
+ logger.error(
+ "triage.lane_failed",
+ entity=entity,
+ error=str(exc),
+ error_type=type(exc).__name__,
+ exc_info=True,
+ )
+ finally:
+ self._release(entity)
+
+ task = asyncio.create_task(_run())
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
+ return task
+
+ async def drain(self) -> None:
+ """Wait for everything in flight.
+
+ Called before an offset commit: committing while work is in
+ flight is the at-least-once contract broken, because a crash
+ after the commit loses an alert that was never triaged.
+ """
+ while self._tasks:
+ await asyncio.gather(*tuple(self._tasks), return_exceptions=True)
diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.py
index 8d172d9df..1252c6928 100644
--- a/services/agents/app/workers/fused_alert_consumer.py
+++ b/services/agents/app/workers/fused_alert_consumer.py
@@ -35,6 +35,7 @@ import asyncio
import contextlib
import json
import os
+import time
import uuid
from datetime import UTC, datetime
from typing import Any
@@ -62,6 +63,7 @@ from app.playbook import alert_trigger
from app.routing.model_router import is_deterministic_mode
from app.security.llm_resolver import resolve_llm_config
from app.workers.business_context import BusinessContextApplier
+from app.workers.entity_lane import EntityLanes, entity_of
from app.workers.shadow_mode import (
LiveShadowModePolicy,
ShadowDecision,
@@ -78,6 +80,12 @@ from app.workers.triage_persistence import (
logger = structlog.get_logger()
+#: How long the commit window may stay open when the topic is quieter
+#: than the concurrency bound. A policy choice: five seconds of replay
+#: after a crash is cheap, and leaving finished work uncommitted
+#: indefinitely is not.
+_COMMIT_WINDOW_SECONDS = 5.0
+
_NAMESPACE = uuid.uuid5(uuid.NAMESPACE_URL, "tryaisoc.com/agents/auto-triage")
# Idempotency key component (issue #571): the deterministic run_id is derived
@@ -348,6 +356,7 @@ class FusedAlertTriageWorker:
writer: TriageWriter | None = None,
context_reader: TriageContextReader | None = None,
shadow_policy: ShadowModePolicy | None = None,
+ entity_concurrency: int | None = None,
) -> None:
self._bootstrap = bootstrap_servers
self._topic = topic
@@ -368,6 +377,11 @@ class FusedAlertTriageWorker:
# Phase B4 — environment-specific noise reduction applied post-fusion →
# pre-triage. None = disabled (no rules file / flag off).
self._business_context = business_context
+ # Parity 6.9. Concurrency across entities, order within one.
+ # Declared here rather than created in `start` so a test that
+ # builds this worker without a broker still has lanes — the same
+ # reason the sinks above are class-level defaults.
+ self._lanes = EntityLanes(entity_concurrency)
async def start(self) -> None:
from aiokafka import AIOKafkaConsumer # noqa: PLC0415 — optional dep, only at runtime
@@ -386,7 +400,13 @@ class FusedAlertTriageWorker:
await self._consumer.start()
self._running = True
self._attached = True
- logger.info("auto_triage_worker.started", topic=self._topic, group=self._group_id)
+ logger.info(
+ "auto_triage_worker.started",
+ topic=self._topic,
+ group=self._group_id,
+ entity_concurrency=self._lanes.limit,
+ )
+ last_commit = time.monotonic()
try:
async for msg in self._consumer:
if not self._running:
@@ -402,18 +422,59 @@ class FusedAlertTriageWorker:
# of another method: the loop must not depend on a callee
# staying total, which is exactly how the ueba consumer came
# to have no ``except`` on its only handler.
- try:
- await self._process_with_retry(msg.value)
- except Exception as exc: # noqa: BLE001 — one alert must not end the subscription
- _METRICS["errors"] += 1
- logger.error(
- "auto_triage_worker.handler_escaped",
- error=str(exc),
- error_type=type(exc).__name__,
- partition=getattr(msg, "partition", None),
- offset=getattr(msg, "offset", None),
- exc_info=True,
- )
+ # Parity 6.9. Triage is an LLM call, so this stage spends
+ # almost all of its time waiting; it used to wait one alert
+ # at a time. Alerts about *different* entities now run
+ # concurrently up to a bound, and alerts about one entity
+ # still run in arrival order — they are the ones most
+ # likely to be one incident, and triage reads institutional
+ # memory that earlier triages of the same entity wrote, so
+ # racing them turns a deterministic verdict into a coin
+ # toss.
+ payload = msg.value if isinstance(msg.value, dict) else {}
+ partition = getattr(msg, "partition", None)
+ offset = getattr(msg, "offset", None)
+
+ async def _handle(value=msg.value, partition=partition, offset=offset) -> None:
+ try:
+ await self._process_with_retry(value)
+ except Exception as exc: # noqa: BLE001 — one alert must not end the subscription
+ _METRICS["errors"] += 1
+ logger.error(
+ "auto_triage_worker.handler_escaped",
+ error=str(exc),
+ error_type=type(exc).__name__,
+ partition=partition,
+ offset=offset,
+ exc_info=True,
+ )
+
+ await self._lanes.submit(entity_of(payload), _handle)
+
+ # Commit only after everything in flight has finished, and
+ # only when the window is full or has been open long
+ # enough. Committing with work in flight would break the
+ # at-least-once contract this loop's own comment
+ # describes: a crash after the commit loses an alert that
+ # was never triaged.
+ #
+ # The time bound matters as much as the count. Without it
+ # a topic that goes quiet below the concurrency bound
+ # leaves the last few alerts triaged and uncommitted
+ # indefinitely, so a restart replays work that was already
+ # done — correct, and wasteful every single time.
+ window_full = self._lanes.in_flight >= self._lanes.limit
+ window_old = (time.monotonic() - last_commit) >= _COMMIT_WINDOW_SECONDS
+ if window_full or window_old:
+ await self._lanes.drain()
+ last_commit = time.monotonic()
+ try:
+ await self._consumer.commit()
+ except Exception as commit_exc: # noqa: BLE001 — reprocess on restart
+ logger.warning("auto_triage_worker.commit_failed", error=str(commit_exc))
+ continue
+
+ await self._lanes.drain()
try:
await self._consumer.commit()
except Exception as commit_exc: # noqa: BLE001 — reprocess on restart
diff --git a/services/agents/tests/test_entity_lanes.py b/services/agents/tests/test_entity_lanes.py
new file mode 100644
index 000000000..6c66eec0c
--- /dev/null
+++ b/services/agents/tests/test_entity_lanes.py
@@ -0,0 +1,198 @@
+"""Triage runs concurrently across entities and in order within one.
+
+Parity 6.9. The property that matters is not "it is faster" — it is that
+making it faster did not reorder the alerts whose order is load-bearing.
+Two alerts about one host are the ones most likely to be one incident,
+and triage reads institutional memory earlier triages of the same entity
+wrote, so racing them turns a deterministic verdict into a coin toss.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from app.workers.entity_lane import (
+ DEFAULT_MAX_CONCURRENCY,
+ MAX_CONCURRENCY_CEILING,
+ EntityLanes,
+ configured_concurrency,
+ entity_of,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+async def test_alerts_about_one_entity_run_in_arrival_order():
+ lanes = EntityLanes(max_concurrency=8)
+ order: list[int] = []
+
+ def work(index: int, delay: float):
+ async def _run() -> None:
+ await asyncio.sleep(delay)
+ order.append(index)
+
+ return _run
+
+ # The first is the slowest. Without the lane it would finish last.
+ await lanes.submit("WS-014", work(1, 0.05))
+ await lanes.submit("WS-014", work(2, 0.01))
+ await lanes.submit("WS-014", work(3, 0.0))
+ await lanes.drain()
+
+ assert order == [1, 2, 3], f"one entity's alerts were reordered: {order}"
+
+
+async def test_alerts_about_different_entities_overlap():
+ lanes = EntityLanes(max_concurrency=8)
+ started: list[str] = []
+ release = asyncio.Event()
+
+ def work(name: str):
+ async def _run() -> None:
+ started.append(name)
+ await release.wait()
+
+ return _run
+
+ await lanes.submit("host-a", work("a"))
+ await lanes.submit("host-b", work("b"))
+ # Let both tasks reach their first await.
+ await asyncio.sleep(0.02)
+ both_running = sorted(started)
+ release.set()
+ await lanes.drain()
+
+ assert both_running == ["a", "b"], f"only {started} started; different entities are being serialised"
+
+
+async def test_concurrency_is_bounded():
+ lanes = EntityLanes(max_concurrency=2)
+ peak = 0
+ current = 0
+ release = asyncio.Event()
+
+ def work():
+ async def _run() -> None:
+ nonlocal peak, current
+ current += 1
+ peak = max(peak, current)
+ await release.wait()
+ current -= 1
+
+ return _run
+
+ for i in range(6):
+ await lanes.submit(f"host-{i}", work())
+ await asyncio.sleep(0.02)
+ observed = peak
+ release.set()
+ await lanes.drain()
+
+ assert observed == 2, f"peak concurrency {observed}; an unbounded fan-out rate-limits the provider"
+
+
+async def test_a_failing_alert_does_not_take_the_lane_or_the_loop_down():
+ lanes = EntityLanes(max_concurrency=4)
+ done: list[str] = []
+
+ async def boom() -> None:
+ raise RuntimeError("triage blew up")
+
+ async def fine() -> None:
+ done.append("second")
+
+ await lanes.submit("WS-014", boom)
+ await lanes.submit("WS-014", fine)
+ await lanes.drain()
+
+ assert done == ["second"], "a failing alert stopped the entity's lane"
+
+
+async def test_lanes_do_not_accumulate_for_every_host_ever_seen():
+ """A long-running deployment must not hold one lock per host it has
+ ever processed."""
+ lanes = EntityLanes(max_concurrency=4)
+
+ async def nothing() -> None:
+ return None
+
+ for i in range(50):
+ await lanes.submit(f"host-{i}", nothing)
+ await lanes.drain()
+
+ assert lanes.tracked_entities == 0, f"{lanes.tracked_entities} lanes retained after draining"
+
+
+async def test_drain_waits_for_everything():
+ lanes = EntityLanes(max_concurrency=4)
+ finished: list[int] = []
+
+ def work(i: int):
+ async def _run() -> None:
+ await asyncio.sleep(0.01)
+ finished.append(i)
+
+ return _run
+
+ for i in range(10):
+ await lanes.submit(f"host-{i % 3}", work(i))
+ await lanes.drain()
+
+ assert len(finished) == 10
+ assert lanes.in_flight == 0
+
+
+# ---------------------------------------------------------------------------
+# Entity resolution. It has to be the same field fusion correlates on.
+# ---------------------------------------------------------------------------
+
+
+ ("alert", "expected"),
+ [
+ ({"src_ip": "198.51.100.4", "hostname": "WS-014"}, "198.51.100.4"),
+ ({"hostname": "WS-014", "username": "alice"}, "WS-014"),
+ ({"username": "alice"}, "alice"),
+ ({"entities": [{"value": "evil.example.com"}]}, "evil.example.com"),
+ ],
+)
+async def test_entity_precedence_matches_the_correlation_key(alert, expected):
+ assert entity_of(alert) == expected
+
+
+async def test_an_alert_naming_nobody_gets_its_own_lane():
+ # It shares an incident with nothing, so there is no order to
+ # preserve — and keying them all together would serialise the lot.
+ a = entity_of({"id": "alert-1"})
+ b = entity_of({"id": "alert-2"})
+ assert a != b
+ assert a == "alert:alert-1"
+
+
+async def test_a_blank_entity_is_not_used():
+ assert entity_of({"hostname": " ", "username": "alice"}) == "alice"
+
+
+# ---------------------------------------------------------------------------
+# Configuration.
+# ---------------------------------------------------------------------------
+
+
+async def test_the_default_applies_when_unset(monkeypatch):
+ monkeypatch.delenv("AISOC_TRIAGE_CONCURRENCY", raising=False)
+ assert configured_concurrency() == DEFAULT_MAX_CONCURRENCY
+
+
[email protected]("bad", ["lots", "0", "-3", str(MAX_CONCURRENCY_CEILING + 1)])
+async def test_an_unusable_override_falls_back_rather_than_clamping_silently(monkeypatch, bad):
+ # Silently clamping a typo would leave an operator who asked for 200
+ # believing they got it.
+ monkeypatch.setenv("AISOC_TRIAGE_CONCURRENCY", bad)
+ assert configured_concurrency() == DEFAULT_MAX_CONCURRENCY
+
+
+async def test_a_valid_override_is_honoured(monkeypatch):
+ monkeypatch.setenv("AISOC_TRIAGE_CONCURRENCY", "3")
+ assert configured_concurrency() == 3
+ assert EntityLanes().limit == 3