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.

fix(agents): cap prompt bytes at egress; dead-letter deterministic 400s (#1554)

alexmateescu021473595534
diff --git a/services/agents/app/llm/contract.py b/services/agents/app/llm/contract.py
index 9bb7b77cc..18d05576e 100644
--- a/services/agents/app/llm/contract.py
+++ b/services/agents/app/llm/contract.py
@@ -97,6 +97,78 @@ __all__ = [
# ---------------------------------------------------------------------------
+# ── Prompt byte cap (egress safety valve) ────────────────────────────────────
+#: Max total bytes of message content allowed to leave toward the inference
+#: gateway. The cap is a ceiling against runaway growth (tool output
+#: accumulating across loop iterations), not a normal-path limit: ordinary
+#: prompts land two orders of magnitude below it. A prompt over the backend's
+#: own limit is rejected wholesale and deterministically, and the retry
+#: storm behind such a rejection burns inference capacity without ever
+#: succeeding — so we truncate the largest contributor here, honestly
+#: marking what was cut, and let the request be answered.
+_MAX_PROMPT_BYTES = int(os.getenv("AISOC_LLM_MAX_PROMPT_BYTES", "240000"))
+_TRUNCATION_MARKER = "\n\n[... truncated: AiSOC prompt byte cap ...]"
+
+
+def _msg_bytes(msg: Any) -> int:
+ content = getattr(msg, "content", msg)
+ if isinstance(content, str):
+ return len(content.encode("utf-8"))
+ if isinstance(content, list):
+ return sum(len(str(p.get("text", "")).encode("utf-8")) for p in content if isinstance(p, dict))
+ return 0
+
+
+def _cap_prompt_bytes(messages: list[Any]) -> list[Any]:
+ """Truncate oversized non-system messages to a fair share until fitting.
+
+ Water-filling rather than greedy: clipping one message to zero while its
+ neighbours stay whole punishes whichever tool happened to answer first.
+ Processing messages largest-first, every message still above the even
+ share of the remaining budget is clipped down to that share, so the cut
+ is spread proportionally across the contributors that are actually big.
+ """
+ if _MAX_PROMPT_BYTES <= 0:
+ return messages
+ sizes = [_msg_bytes(m) for m in messages]
+ total = sum(sizes)
+ if total <= _MAX_PROMPT_BYTES:
+ return messages
+ marker_bytes = len(_TRUNCATION_MARKER.encode("utf-8"))
+ out = list(messages)
+ budget = _MAX_PROMPT_BYTES
+ order: list[int] = []
+ for i, m in enumerate(messages):
+ if getattr(m, "type", "") == "system":
+ budget -= sizes[i]
+ else:
+ order.append(i)
+ order.sort(key=lambda i: (-sizes[i], i))
+ for pos, i in enumerate(order):
+ if not order:
+ break
+ n = len(order) - pos
+ fair = max(0, budget // n)
+ if sizes[i] <= fair:
+ break # everything remaining fits within the even share
+ keep = max(0, fair - marker_bytes)
+ content = getattr(out[i], "content", None)
+ if not isinstance(content, str):
+ continue
+ clipped = content.encode("utf-8")[:keep].decode("utf-8", errors="ignore") + _TRUNCATION_MARKER
+ try:
+ out[i] = out[i].model_copy(update={"content": clipped})
+ except Exception: # noqa: BLE001 — non-pydantic stand-in
+ import copy as _copy
+
+ clone = _copy.copy(out[i])
+ clone.content = clipped
+ out[i] = clone
+ sizes[i] = len(clipped.encode("utf-8"))
+ budget -= sizes[i]
+ return out
+
+
async def safe_ainvoke(llm: Any, messages: Iterable[Any], **kwargs: Any) -> Any:
"""Validate ``messages`` against the contract, then call ``llm.ainvoke``.
@@ -106,6 +178,7 @@ async def safe_ainvoke(llm: Any, messages: Iterable[Any], **kwargs: Any) -> Any:
"""
materialised = list(messages)
LLMInputContract.validate(materialised)
+ materialised = _cap_prompt_bytes(materialised)
model = _model_name(llm)
prompt, user_input = _cache_parts(materialised)
@@ -150,6 +223,7 @@ async def safe_astream(llm: Any, messages: Iterable[Any], **kwargs: Any):
"""Streaming variant of :func:`safe_ainvoke` that yields chunks."""
materialised = list(messages)
LLMInputContract.validate(materialised)
+ materialised = _cap_prompt_bytes(materialised)
egress = egress_privacy.open_session(
model=_model_name(llm),
base_url=getattr(llm, "base_url", None) or getattr(llm, "openai_api_base", None),
@@ -224,6 +298,7 @@ async def safe_chat_completions_request(
materialised = list(messages)
LLMInputContract.validate(materialised)
+ materialised = _cap_prompt_bytes(materialised)
try:
import httpx
diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.py
index 1252c6928..49596bef9 100644
--- a/services/agents/app/workers/fused_alert_consumer.py
+++ b/services/agents/app/workers/fused_alert_consumer.py
@@ -326,6 +326,37 @@ def _hold_severe_for_review_after_llm_failure(state: InvestigationState) -> Inve
return state
+def _is_terminal_request_error(exc: BaseException) -> bool:
+ """True for deterministic 400-class provider rejections.
+
+ A request rejected as *invalid* (bad schema, oversized/context-exceeded
+ prompt, prefill-memory guard, content policy) is rejected because of the
+ request bytes themselves. Replaying identical bytes cannot change the
+ outcome, so retrying only spends queue slots and keeps the inference
+ machine pinned for every *other* alert. The right answer is to
+ dead-letter immediately and keep the stream moving.
+ """
+ err: BaseException | None = exc
+ seen = 0
+ while err is not None and seen < 10:
+ status = getattr(err, "status_code", None) or getattr(getattr(err, "response", None), "status_code", None)
+ if status == 400:
+ return True
+ if type(err).__name__ in {
+ "BadRequestError",
+ "InvalidRequestError",
+ "ContentPolicyViolationError",
+ "ContextOverflowError",
+ }:
+ return True
+ text = str(err).lower()
+ if "prefill memory guard" in text or "context_length_exceeded" in text:
+ return True
+ err = err.__cause__ or err.__context__
+ seen += 1
+ return False
+
+
class FusedAlertTriageWorker:
"""Consumes ``aisoc.alerts.fused`` and auto-triages each alert (copilot)."""
@@ -505,6 +536,16 @@ class FusedAlertTriageWorker:
except Exception as exc: # noqa: BLE001 — retry, then dead-letter
stage = "triage"
last_error = str(exc)
+ if _is_terminal_request_error(exc):
+ logger.error(
+ "auto_triage_worker.triage_terminal_reject",
+ attempt=attempt,
+ error_type=type(exc).__name__,
+ error=last_error[:500],
+ )
+ _METRICS["errors"] += 1
+ await self._send_to_dlq(message, attempts=attempt, stage="triage-terminal", error=last_error)
+ return False
logger.warning("auto_triage_worker.triage_retry", attempt=attempt, error=last_error)
if attempt < self._max_attempts:
await asyncio.sleep(self._retry_backoff(attempt))
diff --git a/services/agents/tests/test_prompt_byte_cap.py b/services/agents/tests/test_prompt_byte_cap.py
new file mode 100644
index 000000000..6d3ba87f9
--- /dev/null
+++ b/services/agents/tests/test_prompt_byte_cap.py
@@ -0,0 +1,67 @@
+"""Prompt byte cap at the safe_ainvoke/safe_astream choke point.
+
+A prompt over the inference backend's limit is rejected wholesale and
+deterministically; the cap truncates the largest non-system contributor
+instead, honestly marked, so the request is answered rather than retried
+into a retry storm (the Oct 2026 prefill-guard incident).
+"""
+
+from __future__ import annotations
+
+from app.llm import contract
+from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
+
+
+def _total_bytes(msgs) -> int:
+ return sum(len(str(getattr(m, "content", "")).encode("utf-8")) for m in msgs)
+
+
+def test_under_cap_is_untouched(monkeypatch):
+ monkeypatch.setattr(contract, "_MAX_PROMPT_BYTES", 10_000)
+ msgs = [
+ SystemMessage(content="sys"),
+ HumanMessage(content="hello"),
+ ToolMessage(content="result", tool_call_id="t1"),
+ ]
+ out = contract._cap_prompt_bytes(msgs)
+ assert [m.content for m in out] == ["sys", "hello", "result"]
+
+
+def test_over_cap_truncates_largest_and_keeps_system(monkeypatch):
+ monkeypatch.setattr(contract, "_MAX_PROMPT_BYTES", 5_000)
+ big = "X" * 60_000
+ msgs = [
+ SystemMessage(content="system prompt stays verbatim"),
+ HumanMessage(content="small question"),
+ ToolMessage(content=big, tool_call_id="t1"),
+ ]
+ out = contract._cap_prompt_bytes(msgs)
+ assert _total_bytes(out) <= 5_000
+ assert out[0].content == "system prompt stays verbatim"
+ assert out[1].content == "small question"
+ assert out[2].content.endswith("[... truncated: AiSOC prompt byte cap ...]")
+ assert len(out[2].content) < len(big)
+ # original objects are not mutated
+ assert msgs[2].content == big
+
+
+def test_cap_spreads_across_multiple_senders(monkeypatch):
+ monkeypatch.setattr(contract, "_MAX_PROMPT_BYTES", 3_000)
+ msgs = [
+ SystemMessage(content="sys"),
+ ToolMessage(content="A" * 4_000, tool_call_id="t1"),
+ ToolMessage(content="B" * 4_000, tool_call_id="t2"),
+ ]
+ out = contract._cap_prompt_bytes(msgs)
+ assert _total_bytes(out) <= 3_000
+ # both contributors were reduced, order preserved
+ assert out[1].content.startswith("A")
+ assert out[2].content.startswith("B")
+
+
+def test_cap_disabled_when_zero(monkeypatch):
+ monkeypatch.setattr(contract, "_MAX_PROMPT_BYTES", 0)
+ big = "X" * 500_000
+ msgs = [HumanMessage(content=big)]
+ out = contract._cap_prompt_bytes(msgs)
+ assert out[0].content == big
diff --git a/services/agents/tests/test_triage_terminal_400.py b/services/agents/tests/test_triage_terminal_400.py
new file mode 100644
index 000000000..611baaee0
--- /dev/null
+++ b/services/agents/tests/test_triage_terminal_400.py
@@ -0,0 +1,65 @@
+"""Terminal 400-class rejection: dead-letter once, never replay.
+
+The prefill-guard incident replayed identical doomed requests every retry
+attempt. A deterministic request rejection must go straight to the DLQ on
+first sight and stop consuming the inference backend.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.workers import fused_alert_consumer as worker_mod
+from app.workers.fused_alert_consumer import FusedAlertTriageWorker, _is_terminal_request_error
+
+pytestmark = pytest.mark.asyncio
+
+
+class FakeBadRequest(Exception):
+ status_code = 400
+
+
+def _worker(monkeypatch, triage_exc: Exception, max_attempts: int = 3):
+ worker = FusedAlertTriageWorker(bootstrap_servers="ignored", max_attempts=max_attempts)
+ calls = {"triage": 0}
+
+ async def _boom(_msg):
+ calls["triage"] += 1
+ raise triage_exc
+
+ dlq: list[dict] = []
+
+ async def _dlq(message, *, attempts, stage, error):
+ dlq.append({"attempts": attempts, "stage": stage, "error": error})
+
+ monkeypatch.setattr(worker, "triage", _boom)
+ monkeypatch.setattr(worker, "_send_to_dlq", _dlq)
+ monkeypatch.setattr(worker_mod, "_RETRY_BACKOFF_S", 0.0)
+ return worker, calls, dlq
+
+
+async def test_terminal_400_deadletters_without_retry(monkeypatch):
+ worker, calls, dlq = _worker(monkeypatch, FakeBadRequest("prefill memory guard rejected"))
+ ok = await worker._process_with_retry({"id": "alert-1"})
+ assert ok is False
+ assert calls["triage"] == 1 # never replayed
+ assert len(dlq) == 1
+ assert dlq[0]["stage"] == "triage-terminal"
+
+
+async def test_retryable_error_still_retries_then_dlqs(monkeypatch):
+ worker, calls, dlq = _worker(monkeypatch, RuntimeError("transient"), max_attempts=3)
+ ok = await worker._process_with_retry({"id": "alert-2"})
+ assert ok is False
+ assert calls["triage"] == 3
+ assert dlq[0]["stage"] == "triage"
+
+
+async def test_wrapped_bad_request_detected_through_cause_chain():
+ try:
+ try:
+ raise FakeBadRequest("context_length_exceeded")
+ except FakeBadRequest as inner:
+ raise RuntimeError("wrapper") from inner
+ except RuntimeError as outer:
+ assert _is_terminal_request_error(outer) is True
+ assert _is_terminal_request_error(RuntimeError("network blip")) is False