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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Make a retry loop say whether waiting will help, and read the one place a dead path could hide (#864)
Beenu Arora3b2816e21f87
diff --git a/.github/workflows/comment-paths.yml b/.github/workflows/comment-paths.ymlnew file mode 100644index 000000000..2b548048b--- /dev/null+++ b/.github/workflows/comment-paths.yml@@ -0,0 +1,87 @@+name: Comment paths++# A comment is the one place no other gate reads.+#+# `docker-compose.yml` carried a reference to an ADR under+# `docs/architecture/decisions/`, a path with no directory behind it. Two+# workstreams tripped over it within an hour and it+# had survived every check in the tree: `check_repo_self_links.py` opens+# markdown and matches github.com URLs, lychee resolves links, and neither+# looks at the prose inside source files — which is where most cross-file+# references in this repository actually live.+#+# Separate from link-check.yml on purpose. That workflow's path filter is+# markdown-only and its docs-tree job runs lychee over the whole portal; this+# one has to trigger on source changes, and making link-check do that would+# put a multi-minute network crawl on every code PR.++on:+ pull_request:+ branches: [main, develop]+ paths:+ - '**/*.py'+ - '**/*.go'+ - '**/*.ts'+ - '**/*.tsx'+ - '**/*.js'+ - '**/*.mjs'+ - '**/*.cjs'+ - '**/*.sh'+ - '**/*.sql'+ - '**/*.tf'+ - '**/*.toml'+ - '**/*.yaml'+ - '**/*.yml'+ - '**/Dockerfile'+ - 'scripts/check_comment_paths.py'+ - '.github/workflows/comment-paths.yml'+ push:+ branches: [main]+ paths:+ - '**/*.py'+ - '**/*.go'+ - '**/*.ts'+ - '**/*.tsx'+ - '**/*.js'+ - '**/*.mjs'+ - '**/*.cjs'+ - '**/*.sh'+ - '**/*.sql'+ - '**/*.tf'+ - '**/*.toml'+ - '**/*.yaml'+ - '**/*.yml'+ - '**/Dockerfile'+ - 'scripts/check_comment_paths.py'+ - '.github/workflows/comment-paths.yml'+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: comment-paths-${{ github.ref }}+ cancel-in-progress: true++jobs:+ comment-paths:+ name: Comment paths · repo paths in comments must exist+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ # Full history is not needed, but the gate resolves its root through+ # `git rev-parse` and lists the corpus with `git ls-files`, so it has to+ # run inside a real checkout rather than an unpacked archive.+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0+ with:+ python-version: '3.11'++ # Before the gate, not after: a gate whose own detection has broken+ # reports a clean tree for the same reason a clean tree does.+ - name: Prove the gate still detects what it claims to+ run: python3 scripts/check_comment_paths.py --self-test++ - name: Every repository path named in a comment exists+ run: python3 scripts/check_comment_paths.pydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2c93b7851..750dbf60c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,101 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **A gate that reads the one place a dead path could get in.** A comment is+ the only prose no check in this tree opens: `check_repo_self_links.py`+ reads markdown and matches `github.com` URLs, lychee resolves links, and+ neither looks inside source files — which is where most cross-file+ references in this repository actually live. That is how+ `docker-compose.yml` came to name+ `docs/architecture/decisions/0001-llm-gateway-in-core.md`, a path with no+ directory behind it, and survive every gate. `scripts/check_comment_paths.py`+ reads comments in fourteen languages plus Python docstrings and asserts+ that every repository path they name exists.+ The corpus was measured before the gate was written, because a naive+ version would have been mostly noise: of **3,092** path-shaped strings in+ non-markdown comments, most are MIME types, MCP method names+ (`tools/call`), Splunk REST routes (`services/search/jobs`), container+ images or URL routes. Three structural filters — a known file extension, a+ first segment that names something at the top of this repository, and not+ a URL / template / glob / gitignored artefact — cut that to **1,251**+ claims about this tree, resolved against the repository root *and* each+ ancestor of the referring file (a comment in `services/agents/tests/`+ saying `tests/conftest.py` means the one beside it).+ Extension-less directory references are **deliberately not checked** and+ the gate says so in its own output: 286 resolve and 52 do not, and+ hand-classifying the 52 put genuine rot at roughly one in five, which is+ the precision at which a gate gets ignored.+ Ten exceptions are recorded, each with a reason and each verified in both+ directions — an entry whose path now resolves, or which no longer appears+ in any comment, fails the build rather than sitting there.++### Fixed++- **A consumer that retried a permanent failure in silence, forever.** The+ `graph_ws` broadcaster in `services/ingest` could not die the way the UEBA+ consumer did — its loop `continue`s past an error — but it answered every+ error the same way: a flat 50ms sleep with the error discarded. Against a+ broker that was never coming back that is twenty reconnect attempts a+ second behind a container reporting `running`, restarts 0 and `/health`+ 200, with no line in any log and no counter anywhere. Not a silent death;+ a permanent failure wearing the costume of a transient one.+ Most of those errors never reached the loop at all. `kafka.NewReader`+ falls back to a **silent logger** when `ErrorLogger` is nil, and with a+ `GroupID` set the consumer group's dial, join and rebalance failures are+ reported *only* through it — `ReadMessage` stays blocked — so the single+ most likely permanent fault, an unreachable or misnamed broker, was+ discarded inside the library. `ErrorLogger` is now wired.+ Errors are classified into what the loop can do about them: **transient**+ (retry, with exponential backoff capped at 30s instead of a flat 50ms),+ **permanent** (the loop stops, because a loop over a fault no retry can+ clear turns a misconfiguration into indefinite churn — the same reasoning+ the UEBA consumer records), and **poison** (one undecodable envelope,+ counted and skipped without backing off a healthy subscription). A fourth+ state is a duration rather than a class: a `no such host` can be a startup+ race for a few seconds and a variable nobody set for ever, so it is+ reported as transient and then, after two minutes, as *not resolving* —+ the point at which the operator's next move stops being "wait".+ Permanence is decided by an enumerated set of protocol codes, not by+ negating `kafka.Error.Temporary()`: `REBALANCE_IN_PROGRESS` is+ non-retriable in the protocol's sense and happens on every deploy, so+ deriving the set that way would have stopped the consumer on a routine+ rebalance. A test walks the entire error table in both directions.+- **Readiness that reported on the process and not on the subscription.**+ Ingest's `/readyz` now names every registered background subscription and+ its state, in the healthy case too, so a 200 says what was checked rather+ than only that nothing was wrong. The verdict stays keyed on the publish+ path deliberately: unlike the Python services, consuming is not ingest's+ job, and failing readiness for an opt-in WebSocket fan-out would pull the+ pipeline's front door out of the load balancer to fix a broadcast. The+ surface that depends on the subscription reports on it directly —+ `/v1/graph_ws/stream` answers 503 with the reason instead of completing a+ handshake onto a socket that will stay silent — and+ `aisoc_graph_ws_source_attached` / `_errors_total` / `_not_resolving` are+ the alertable signals.+- **Two scheduler loops that logged that a tick failed and never what.**+ `retention_purge` and `hunt_scheduler` logged `err=%s` with+ `type(exc).__name__` and nothing else: `err=ProgrammingError` every thirty+ seconds says a tick failed, never why, and never whether waiting is the+ right response. Both now report the sanitised message and escalate from+ `warning` to `error` once the run of failures has outlived a transient+ explanation.+- **Twenty-two dead paths in comments and docstrings**, found by the new+ gate on its first run. Among them: cost provenance pointing at migration+ `055` when the file is `063`; the Wazuh severity table pointing at+ `apps/docs/connectors/` instead of `apps/docs/docs/connectors/`; eight+ copies of the vendored `tenant_scope.py` pointing at a+ `check_vendored_tenant_scope.py` that is spelled `sync_`; eleven files+ pointing at a root-level `tests/test_security_defaults.py` that lives+ under `services/api/`; and three separate pointers at CI checks that had+ never been written, one of which `check_action_contract.py` already+ documented as fictional in its own docstring.+- **A load generator that could tick forever and send nothing.**+ `services/demo-producer` silently `continue`d when `http.NewRequestWithContext`+ failed, which only happens for a malformed URL — the one error in that+ loop no retry can clear. It now says so and stops.+### Changed- **`sqlglot` moved to the 30 line across all eight declarations, and thediff --git a/apps/web/public/sw.js b/apps/web/public/sw.jsindex ef8dd5973..28c4ae892 100644--- a/apps/web/public/sw.js+++ b/apps/web/public/sw.js@@ -288,7 +288,8 @@ self.addEventListener('sync', (event) => {async function replayQueuedApprovals() {// Approval mutations made while offline are stored in IndexedDB by the// /responder views; on reconnection we drain the queue here. The actual- // queue impl lives in apps/web/src/lib/responder/offlineQueue.ts.+ // queue impl lives in apps/web/src/lib/pwa.ts (queueApproval /+ // listQueuedApprovals over the 'pending-approvals' IndexedDB store).const clients = await self.clients.matchAll();clients.forEach((c) => c.postMessage({ type: 'sync-approvals' }));}diff --git a/apps/web/src/components/connectors/ConnectorInstanceList.tsx b/apps/web/src/components/connectors/ConnectorInstanceList.tsxindex 80a5fd658..266a16e17 100644--- a/apps/web/src/components/connectors/ConnectorInstanceList.tsx+++ b/apps/web/src/components/connectors/ConnectorInstanceList.tsx@@ -98,8 +98,8 @@ function formatDurationSeconds(secs: number | null | undefined): string {/*** Tailwind classes for the three rendered freshness states.*- * Centralised so the legend in docs/connectors/freshness-slos.md can- * mirror these exact swatches. ``unknown`` deliberately has no row —+ * Centralised so every surface rendering a freshness badge reads the+ * same three swatches. ``unknown`` deliberately has no row —* we don't render that variant so a freshly-saved connector with no* events yet looks clean instead of being painted gray "stale."*/diff --git a/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.py b/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.pyindex 01dd8b516..20e1d8538 100644--- a/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.py+++ b/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.py@@ -13,7 +13,7 @@ is the CLI's high-level entry point.The "LLM" used here is :class:`DeterministicReasoner`, a tinytemplate-driven stub. The real agents call out to OpenAI / Anthropic /Ollama via LiteLLM with a guarded prompt contract — see-``services/agents/app/services/llm_safety.py``. The sandbox does not+``services/api/app/services/llm_safety.py``. The sandbox does notmake any network calls."""diff --git a/packages/aisoc-sandbox/tests/test_smoke.py b/packages/aisoc-sandbox/tests/test_smoke.pyindex e4659cd39..7213f7e0e 100644--- a/packages/aisoc-sandbox/tests/test_smoke.py+++ b/packages/aisoc-sandbox/tests/test_smoke.py@@ -3,7 +3,7 @@If any of these fail, `pip install aisoc-sandbox && aisoc-sandbox demo`no longer works on a clean machine — which is the only contract thatmatters for this package. The CI gate that runs this suite on a Linux-+ macOS matrix (see `.github/workflows/sandbox-smoke.yml`) is the++ macOS matrix (see the `sandbox-offline` job in `.github/workflows/readme-gates.yml`) is theauthoritative trust signal for the `pip install` path."""diff --git a/scripts/audit_health_probes.py b/scripts/audit_health_probes.pyindex bfaeaa2df..ef56f3d82 100644--- a/scripts/audit_health_probes.py+++ b/scripts/audit_health_probes.py@@ -84,8 +84,8 @@ def audit_service(svc: str, reference: bytes | None) -> tuple[bool, bool, bool,tree would have left the other twelve serving the older contract, and aprobe that answers differently per service is worse than one that iswrong everywhere — it makes a fleet-wide readiness answer unreadable.- The docstring also pointed at ``scripts/sync_health_module.py``, which- does not exist in this tree.+ The docstring also pointed at a sync script under ``scripts/`` that was+ never written, so the sync it promised had no implementation either."""base = SERVICES_DIR / svc / "app"module = base / "_health.py"diff --git a/scripts/check_action_contract.py b/scripts/check_action_contract.pyindex abce202cb..eaf2aeead 100644--- a/scripts/check_action_contract.py+++ b/scripts/check_action_contract.py@@ -667,11 +667,11 @@ def _ratchet(name: str, baseline: dict[str, str], resolved_set: set[str]) -> lisdef check_capability_mirror() -> list[str]:"""The actions mirror must match the connectors Capability enum.- capabilities.py documents a CI check at- ``services/actions/tests/test_capability_mirror.py`` that compares the two- sets. No such file exists, so the mirror it describes has never been- verified — which is how four reverse verbs the action contracts name- ended up missing from both.+ capabilities.py used to document this check as a test file under+ ``services/actions/tests`` that had never been written, so the mirror it+ described had never been verified — which is how four reverse verbs the+ action contracts name ended up missing from both. This function is the+ check; capabilities.py now points at it."""import importlib.utildiff --git a/scripts/check_comment_paths.py b/scripts/check_comment_paths.pynew file mode 100644index 000000000..a6e5f00d8--- /dev/null+++ b/scripts/check_comment_paths.py@@ -0,0 +1,673 @@+#!/usr/bin/env python3+"""Every repository path named in a code comment must exist.++Why this exists as a separate gate+----------------------------------+``docker-compose.yml`` carried a reference to an ADR under+``docs/architecture/decisions/`` — a path with no directory behind it. Two+workstreams tripped over it within an hour, and it had survived every check+in the tree, because **a comment is the one place no gate reads**.+``check_repo_self_links.py`` opens markdown and matches+``github.com/...`` URLs; lychee resolves links; nothing had ever looked at+the prose inside source files, which is where most cross-file references in+this repository actually live.++That prose is load-bearing. "Keep this in sync with X", "the operator table+lives at Y", "CI check Z compares the two sets" — each is an instruction to+the next contributor, and each is worthless the moment the path is wrong. On+its first run this gate found nine dead references in comments and thirteen+more in Python docstrings, including a migration renumbered 055 → 063, a+connector doc that moved under ``apps/docs/docs/``, and three separate+pointers at CI checks that had never been written.++What it reads, and what it deliberately does not+------------------------------------------------+The corpus was measured before the gate was written, because a naive version+would have been mostly noise. Of **3,092** path-shaped strings in non-+markdown comments, most are not repository paths at all: MIME types, MCP+method names (``tools/call``), Splunk REST routes (``services/search/jobs``),+container images, URL routes, Go import paths. Flagging those would produce a+gate people learn to ignore, which is worse than none.++Three structural filters cut the corpus to the references that are actually+claims about this tree:++1. **A known file extension.** ``tools/call`` and ``services/ocsf`` are not+ files. This is also what excludes ``cost_telemetry._PRICING`` and+ ``graph_ws.Broadcaster``, which are attribute references wearing a slash.+2. **A first segment that names something at the top of this repository.**+ ``application/json`` and ``github.com/x/y`` do not survive it; the+ ``docs/…`` reference that started this does.+3. **Not a URL, not templated, not a glob, not gitignored.** A build artefact+ under ``dist/`` legitimately does not exist in a clean checkout.++A path is then resolved against the repository root *and* against each+ancestor of the file that mentions it, because a comment in+``services/agents/tests/`` naming a ``conftest.py`` under ``tests/`` means+the one beside it, not one at the root.++Measured blind spot, accepted on purpose+----------------------------------------+Extension-less directory references — ``infra/terraform/aws``,+``services/ocsf`` — are **not** checked. 286 of them resolve and 52 do not,+and hand-classifying the 52 put genuine rot at roughly one in five: the rest+are URL routes, API paths and tool names that happen to start with a+directory name. A gate at 20% precision is a gate that gets ignored, so this+one says what it skipped (see the summary it prints) rather than guessing.++Exceptions+----------+``ACCEPTED`` records the references that are deliberately unresolvable:+placeholders in usage text, and prose *about* a path that was removed or+moved. Each carries a reason and is checked in both directions — an entry+naming a reference that now resolves, or one that is no longer in the+corpus, fails the build rather than sitting there.++Usage+-----+ python3 scripts/check_comment_paths.py+ python3 scripts/check_comment_paths.py --list # every reference read+ python3 scripts/check_comment_paths.py --self-test # prove it still detects++Exit codes: 0 clean, 1 findings, 2 the scan itself could not run.+"""++from __future__ import annotations++import argparse+import ast+import re+import subprocess+import sys+from dataclasses import dataclass+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402++# --------------------------------------------------------------------------+# Corpus definition+# --------------------------------------------------------------------------+#: (line-comment token, block-comment delimiters) per extension. A language+#: absent from here is not read, and the summary says how many files that was.+COMMENT_SYNTAX: dict[str, tuple[str | None, tuple[str, str] | None]] = {+ ".py": ("#", None),+ ".sh": ("#", None),+ ".bash": ("#", None),+ ".yaml": ("#", None),+ ".yml": ("#", None),+ ".toml": ("#", None),+ ".tf": ("#", None),+ ".ini": ("#", None),+ ".cfg": ("#", None),+ ".go": ("//", ("/*", "*/")),+ ".ts": ("//", ("/*", "*/")),+ ".tsx": ("//", ("/*", "*/")),+ ".js": ("//", ("/*", "*/")),+ ".mjs": ("//", ("/*", "*/")),+ ".cjs": ("//", ("/*", "*/")),+ ".sql": ("--", ("/*", "*/")),+}++#: Files with no extension that are still comment-bearing.+COMMENT_FILENAMES = {"Dockerfile": ("#", None), "Makefile": ("#", None)}++#: An archived prototype subtree kept for history; its paths describe a repo+#: that no longer exists. CodeQL excludes it for the same reason.+EXCLUDED_PREFIXES = ("plans/cyble-aisoc/",)++#: Suffixes that make a token a plausible file reference. Anything else is+#: either not a file or a directory, and directories are the measured blind+#: spot documented above.+FILE_SUFFIXES = frozenset(+ {+ ".py",+ ".go",+ ".ts",+ ".tsx",+ ".js",+ ".mjs",+ ".cjs",+ ".md",+ ".mdx",+ ".yaml",+ ".yml",+ ".json",+ ".sql",+ ".sh",+ ".tf",+ ".toml",+ ".ini",+ ".cfg",+ ".txt",+ ".lock",+ ".tmpl",+ ".tpl",+ ".mod",+ ".sum",+ ".css",+ ".html",+ ".svg",+ ".png",+ }+)++#: A path-shaped run of characters. The first segment is deliberately+#: narrower than the rest: a leading `(` or `[` is punctuation around the+#: reference, while `apps/web/src/app/(app)/…` is a real Next.js route group.+TOKEN_RE = re.compile(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.()\[\]-]+)+")++#: Trailing punctuation a sentence leaves attached to a path.+TRAILING = "`'\"),;:.]}>"++#: A scheme, or a dotted host followed by a slash, immediately before the+#: token — in which case the token is part of a URL and not our path.+URL_PREFIX_RE = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*://\S*|[A-Za-z0-9-]+\.[A-Za-z]{2,}/\S*)$")+++# --------------------------------------------------------------------------+# Recorded exceptions. Shrink-only, checked in both directions.+# --------------------------------------------------------------------------+#: Keyed ``(file, token) -> reason``. An entry whose reference now resolves,+#: or which no longer appears in the corpus at all, is a finding: a stale+#: exception is how a list stops describing the tree it excuses.+ACCEPTED: dict[tuple[str, str], str] = {+ (".github/workflows/screencast.yml", "apps/web/pnpm-lock.yaml"): (+ "Prose asserting the file's absence — the sentence is 'apps/web/pnpm-lock.yaml does not "+ "exist', which is the fact the step depends on."+ ),+ ("apps/web/eslint.config.mjs", "apps/web/.eslintrc.json"): (+ "Names the file this config replaced. The reference is historical and rewriting it to a "+ "path that exists would lose the only record of the migration."+ ),+ ("infra/fly/managed/provision.sh", "infra/fly/managed/tenants/acme.yaml"): (+ "A placeholder tenant file in the usage line. Real tenant descriptors are supplied by the "+ "operator and are not committed."+ ),+ ("infra/fly/managed/render.sh", "infra/fly/managed/tenants/acme.yaml"): (+ "Same usage line in the sibling script, same placeholder."+ ),+ ("scripts/audit_runbook_links.py", "docs/runbooks/foo.md"): (+ "An illustrative path in a docstring explaining which link shapes the gate accepts."+ ),+ ("scripts/check_competitor_names.py", "docs/connectors/x.md"): (+ "An illustrative path in a docstring explaining glob semantics: 'docs/connectors/** matches "+ "docs/connectors/x.md'."+ ),+ ("scripts/check_gate_contract.py", "scripts/foo.py"): (+ "An illustrative path in a docstring showing what shlex returns for a quoted path inside an "+ "echo. Naming a real script would make the example read as a claim about that script."+ ),+ ("scripts/check_repo_self_links.py", "services/api/app/api/deps.py"): (+ "Prose recording the dead link that motivated that gate — the path moved under v1/, and the "+ "sentence is about it having moved."+ ),+ ("tools/detection_import/splunk_importer.py", "detections/cloud/foo.yml"): (+ "An illustrative path in a docstring showing how a category is derived from a rule path."+ ),+ ("scripts/aisoc-demo.ts", "apps/web/public/screenshots/01-alerts-queue.png"): (+ "An output destination, not an existing file: `--screenshots` writes the four PNGs there "+ "from a live stack. The directory ships SVG placeholders until someone runs it, which "+ "apps/web/public/screenshots/README.md states."+ ),+}+++# --------------------------------------------------------------------------+# Reading the corpus+# --------------------------------------------------------------------------+@dataclass(frozen=True)+class Reference:+ """One path-shaped token found in one comment."""++ file: str+ line: int+ token: str+ context: str+++class ScanError(RuntimeError):+ """The scan could not be set up. Never downgraded to a clean result."""+++def tracked_files(root: Path) -> list[str]:+ out = subprocess.run( # noqa: S603 - fixed argv, no shell+ ["git", "ls-files"],+ cwd=root,+ capture_output=True,+ text=True,+ check=False,+ )+ if out.returncode != 0:+ raise ScanError(f"cannot list tracked files under {root}: {out.stderr.strip()}")+ return [f for f in out.stdout.splitlines() if f and not f.startswith(EXCLUDED_PREFIXES)]+++def ignored_paths(root: Path, candidates: list[str]) -> set[str]:+ """Which candidates git would ignore. One subprocess, not one per path.++ A reference to ``services/mcp/dist/index.js`` is correct and unresolvable+ at the same time: the file is a build artefact that exists at runtime and+ never in a checkout. Asking git keeps that judgement structural instead of+ becoming a second list of directory names to maintain.+ """+ if not candidates:+ return set()+ out = subprocess.run( # noqa: S603 - fixed argv, no shell+ ["git", "check-ignore", "--stdin"],+ cwd=root,+ input="\n".join(candidates),+ capture_output=True,+ text=True,+ check=False,+ )+ return {line.strip() for line in out.stdout.splitlines() if line.strip()}+++def comment_text(path: Path, ext: str) -> list[tuple[int, str]]:+ """Every comment in the file, as (line number, comment body).++ Crude on purpose: a ``#`` inside a string literal is read as a comment.+ That costs nothing, because the token still has to survive three+ structural filters and then fail to resolve before it is reported.+ """+ line_token, block = COMMENT_SYNTAX.get(ext, COMMENT_FILENAMES.get(path.name, (None, None)))+ try:+ text = path.read_text(encoding="utf-8")+ except (UnicodeDecodeError, OSError):+ return []+ out: list[tuple[int, str]] = []+ in_block = False+ for lineno, line in enumerate(text.splitlines(), start=1):+ rest = line+ if block:+ if in_block:+ end = rest.find(block[1])+ if end >= 0:+ out.append((lineno, rest[:end]))+ in_block = False+ rest = rest[end + len(block[1]) :]+ else:+ out.append((lineno, rest))+ continue+ start = rest.find(block[0])+ if start >= 0:+ end = rest.find(block[1], start + len(block[0]))+ if end >= 0:+ out.append((lineno, rest[start + len(block[0]) : end]))+ rest = rest[:start] + " " + rest[end + len(block[1]) :]+ else:+ out.append((lineno, rest[start + len(block[0]) :]))+ in_block = True+ continue+ if line_token:+ found = re.search(r"(?:^|\s)" + re.escape(line_token), rest)+ if found:+ out.append((lineno, rest[found.end() :]))+ return out+++def docstring_text(path: Path) -> list[tuple[int, str]]:+ """Every Python docstring, as (line number, line).++ Docstrings are the same invisible prose as comments and carry more of it:+ they held thirteen of the twenty-two dead references this gate found on+ its first run, including every 'keep these copies in sync' pointer.+ """+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ except (SyntaxError, UnicodeDecodeError, OSError, ValueError):+ return []+ out: list[tuple[int, str]] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Module | ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):+ continue+ doc = ast.get_docstring(node, clean=False)+ if not doc:+ continue+ first = getattr(node.body[0], "lineno", 1) if node.body else 1+ # The literal's lineno is its last line for a multi-line string in+ # some versions; anchoring at the node keeps the number close enough+ # to find the text, which is all a reader needs.+ start = first - doc.count("\n")+ for offset, line in enumerate(doc.splitlines()):+ out.append((max(1, start + offset), line))+ return out+++def extract(root: Path, files: list[str]) -> tuple[list[Reference], dict[str, int]]:+ """Every path-shaped token in every comment and docstring we can read."""+ refs: list[Reference] = []+ counts = {"files_read": 0, "files_skipped_unknown_syntax": 0, "tokens_seen": 0}+ for rel in files:+ path = root / rel+ ext = path.suffix+ readable = ext in COMMENT_SYNTAX or path.name in COMMENT_FILENAMES+ if not readable:+ counts["files_skipped_unknown_syntax"] += 1+ continue+ counts["files_read"] += 1+ lines = comment_text(path, ext)+ if ext == ".py":+ lines += docstring_text(path)+ for lineno, body in lines:+ for match in TOKEN_RE.finditer(body):+ counts["tokens_seen"] += 1+ token = match.group(0).rstrip(TRAILING)+ if not token or URL_PREFIX_RE.search(body[: match.start()]):+ continue+ refs.append(Reference(file=rel, line=lineno, token=token, context=body.strip()[:120]))+ return refs, counts+++# --------------------------------------------------------------------------+# Deciding which references are claims about this tree+# --------------------------------------------------------------------------+def is_repo_path(token: str, toplevel: frozenset[str]) -> bool:+ """Whether this token is asserting that a file exists in this repository.++ Three structural questions, in the order that discards the most: is it a+ URL or a template, does it name a file, and does it start at the top of+ this tree. See the module docstring for the measurement behind each.+ """+ if "://" in token or "$" in token or "{" in token or "*" in token:+ return False+ if Path(token).suffix not in FILE_SUFFIXES:+ return False+ return token.split("/", 1)[0] in toplevel+++def resolve(ref: Reference, known: frozenset[str]) -> str | None:+ """The path this reference names, or None.++ Tried against the repository root first and then against each ancestor of+ the referring file, because a ``tests/`` path named in a comment inside+ ``services/agents/tests/`` means the file beside it.+ """+ if ref.token in known:+ return ref.token+ base = Path(ref.file).parent+ for parent in [base, *base.parents]:+ if str(parent) == ".":+ continue+ candidate = f"{parent}/{ref.token}"+ if candidate in known:+ return candidate+ return None+++def known_paths(files: list[str]) -> frozenset[str]:+ """Every tracked file and every directory containing one."""+ known: set[str] = set(files)+ for rel in files:+ for parent in Path(rel).parents:+ if str(parent) != ".":+ known.add(str(parent))+ return frozenset(known)+++@dataclass+class Result:+ refs_examined: int = 0+ resolved: int = 0+ excused: int = 0+ ignored: int = 0+ missing: list[Reference] = None # type: ignore[assignment]+ stale_exceptions: list[tuple[tuple[str, str], str]] = None # type: ignore[assignment]++ def __post_init__(self) -> None:+ if self.missing is None:+ self.missing = []+ if self.stale_exceptions is None:+ self.stale_exceptions = []+++def judge(+ refs: list[Reference],+ known: frozenset[str],+ toplevel: frozenset[str],+ ignored: frozenset[str],+ accepted: dict[tuple[str, str], str],+) -> Result:+ """Pure verdict over an already-read corpus, so the self-test can drive it."""+ result = Result()+ seen_keys: set[tuple[str, str]] = set()+ resolved_keys: set[tuple[str, str]] = set()+ for ref in refs:+ if not is_repo_path(ref.token, toplevel):+ continue+ result.refs_examined += 1+ key = (ref.file, ref.token)+ seen_keys.add(key)+ if resolve(ref, known) is not None:+ result.resolved += 1+ resolved_keys.add(key)+ continue+ if ref.token in ignored:+ result.ignored += 1+ continue+ if key in accepted:+ result.excused += 1+ continue+ result.missing.append(ref)++ # The other direction. An exception that no longer excuses anything is a+ # claim about the tree that has stopped being true, and leaving it makes+ # the list a liability instead of a control.+ for key, reason in sorted(accepted.items()):+ if key not in seen_keys:+ result.stale_exceptions.append((key, "no longer appears in any comment — remove the entry"))+ elif key in resolved_keys:+ result.stale_exceptions.append((key, "now resolves to a real path — remove the entry"))+ elif not reason.strip():+ result.stale_exceptions.append((key, "carries no reason"))+ return result+++# --------------------------------------------------------------------------+# CLI+# --------------------------------------------------------------------------+def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--repo-root", type=Path, default=None, help="the tree to inspect (default: git rev-parse)")+ parser.add_argument("--list", action="store_true", help="print every reference that was resolved")+ parser.add_argument(SELF_TEST_FLAG, action="store_true", help="prove this gate detects the drift it claims to")+ args = parser.parse_args(argv)++ if args.self_test:+ return self_test()++ root = (args.repo_root or repo_root()).resolve()+ try:+ files = tracked_files(root)+ except ScanError as exc:+ print(f"check_comment_paths: FAILED to run the scan: {exc}", file=sys.stderr)+ return 2++ known = known_paths(files)+ toplevel = frozenset(f.split("/", 1)[0] for f in files)+ refs, counts = extract(root, files)+ candidates = sorted({r.token for r in refs if is_repo_path(r.token, toplevel)})+ ignored = frozenset(ignored_paths(root, candidates))+ result = judge(refs, known, toplevel, ignored, ACCEPTED)++ print(f"repo root {root}")+ print(+ f"corpus {counts['files_read']} comment-bearing file(s) read, "+ f"{counts['files_skipped_unknown_syntax']} with no comment syntax this gate knows"+ )+ print(f" {counts['tokens_seen']} path-shaped token(s) seen, {result.refs_examined} of them repository-path claims")+ print(+ f"verdict {result.resolved} resolve, {result.ignored} name a gitignored build artefact, "+ f"{result.excused} excused, {len(result.missing)} do not"+ )+ print("not checked extension-less directory references (286 resolve / 52 do not, and hand-")+ print(" classifying the 52 put genuine rot near one in five — see the module docstring)")+ print()++ # Say what was opened before saying it was clean. An empty corpus and a+ # clean corpus produce the same "OK" from the same branch otherwise, which+ # is the failure this repository has shipped five times.+ if not counts["files_read"] or not result.refs_examined:+ print(+ f"check_comment_paths: FAIL — read {counts['files_read']} file(s) and found "+ f"{result.refs_examined} repository-path claim(s) under {root}. A clean result over "+ "nothing is not a clean result; check COMMENT_SYNTAX and TOKEN_RE.",+ file=sys.stderr,+ )+ return 1++ if args.list:+ for ref in sorted(refs, key=lambda r: (r.file, r.line)):+ if is_repo_path(ref.token, toplevel) and resolve(ref, known):+ print(f" ok {ref.file}:{ref.line} {ref.token}")+ print()++ if not result.missing and not result.stale_exceptions:+ print(f"check_comment_paths: OK — every repository path named in a comment exists ({result.resolved} checked)")+ return 0++ if result.missing:+ print(f"{len(result.missing)} comment(s) name a path that does not exist:")+ for ref in result.missing:+ print(f" {ref.file}:{ref.line} -> {ref.token}")+ print(f" {ref.context}")+ print("\nA comment is an instruction to the next contributor. Fix the path, or record it")+ print("in ACCEPTED with the reason it cannot resolve.")++ if result.stale_exceptions:+ print(f"\n{len(result.stale_exceptions)} recorded exception(s) no longer describe the tree:")+ for (file, token), why in result.stale_exceptions:+ print(f" {file} -> {token}: {why}")+ return 1+++# --------------------------------------------------------------------------+# Self-test+# --------------------------------------------------------------------------+def self_test() -> int:+ """Inject each defect this gate exists to catch, and each it must not.++ Every case builds its corpus from a fresh constructor. A shared reference+ list mutated between cases would let one case poison the baseline and+ every later case would 'catch' an inherited finding rather than its own.+ """+ # Mirrors the real tree closely enough to be meaningful: `tests` is a+ # top-level directory in this repository, which is what lets a+ # package-relative conftest reference be examined at all.+ toplevel = frozenset({"docs", "services", "apps", "scripts", "tests"})+ known = frozenset(+ {+ "docs",+ "docs/architecture",+ "docs/architecture/overview.md",+ "services",+ "services/agents",+ "services/agents/tests",+ "services/agents/tests/conftest.py",+ "scripts",+ "scripts/check_comment_paths.py",+ "tests",+ }+ )++ def ref(file: str, token: str, line: int = 1) -> Reference:+ return Reference(file=file, line=line, token=token, context=f"see {token}")++ def run(refs: list[Reference], *, ignored: frozenset[str] = frozenset(), accepted: dict | None = None) -> Result:+ return judge(refs, known, toplevel, ignored, dict(accepted or {}))++ checks: list[tuple[str, bool]] = []++ baseline = run([ref("services/agents/main.py", "docs/architecture/overview.md")])+ checks.append(("the unperturbed baseline reports nothing", not baseline.missing and baseline.resolved == 1))++ # --- what it must flag -------------------------------------------------+ dead = run([ref("docker-compose.yml", "docs/architecture/decisions/0001-llm-gateway-in-core.md")])+ checks.append(+ (+ "the compose comment that started this — a path with no directory behind it",+ [r.token for r in dead.missing] == ["docs/architecture/decisions/0001-llm-gateway-in-core.md"],+ )+ )++ renumbered = run([ref("services/agents/x.py", "services/api/migrations/055_cost_provenance.sql")])+ checks.append(("a migration referenced by a number it no longer has", len(renumbered.missing) == 1))++ # --- what it must NOT flag: enumerate what it credits -------------------+ # This direction is the one that finds the blind spot. A gate that flagged+ # everything would pass every case above.+ credited = [+ ("a MIME type", ref("services/api/x.py", "application/json")),+ ("an MCP method name", ref("services/mcp/src/server.ts", "tools/call")),+ ("a Splunk REST route", ref("services/connectors/x.py", "services/search/jobs")),+ ("a Go import path", ref("services/ingest/main.go", "github.com/segmentio/kafka-go")),+ ("a container image", ref("infra/x.yaml", "ghcr.io/beenuar/aisoc-devcontainer")),+ ("a glob", ref("scripts/x.py", "services/**/*.py")),+ ("a templated path", ref("scripts/x.py", "services/${SERVICE}/app.py")),+ ("an attribute reference wearing a slash", ref("x.py", "services/api/app/core/config.is_dev_env")),+ ("an extension-less directory reference (the accepted blind spot)", ref("x.py", "infra/terraform/aws")),+ ("a URL route", ref("apps/web/x.tsx", "playbooks/new")),+ # Conservative by construction: a package-relative reference whose+ # first segment names nothing at the top of the tree is skipped+ # rather than guessed at. A miss, not a false positive, and recorded+ # here so the trade is visible rather than discovered.+ ("a relative path anchored at no top-level name", ref("services/agents/x.py", "internal/helper.py")),+ ]+ for label, reference in credited:+ outcome = run([reference])+ checks.append((f"does not flag {label}", not outcome.missing and outcome.refs_examined == 0))++ # A path relative to the referring package resolves, and is not a finding.+ relative = run([ref("services/agents/tests/test_x.py", "tests/conftest.py")])+ checks.append(("a package-relative path resolves against the referring file", not relative.missing and relative.resolved == 1))++ # A gitignored build artefact is correct and unresolvable at once.+ artefact = run([ref("services/mcp/src/config.ts", "services/mcp/dist/config.js")], ignored=frozenset({"services/mcp/dist/config.js"}))+ checks.append(("a gitignored build artefact is not a finding", not artefact.missing and artefact.ignored == 1))++ # --- the exceptions ratchet, both directions ---------------------------+ excused = run([ref("a.sh", "docs/nope.md")], accepted={("a.sh", "docs/nope.md"): "recorded reason"})+ checks.append(("a recorded exception suppresses its own finding", not excused.missing and excused.excused == 1))++ now_real = run(+ [ref("services/agents/main.py", "docs/architecture/overview.md")],+ accepted={("services/agents/main.py", "docs/architecture/overview.md"): "recorded reason"},+ )+ checks.append(("an exception whose path now resolves is reported stale", len(now_real.stale_exceptions) == 1))++ vanished = run([], accepted={("gone.py", "docs/gone.md"): "recorded reason"})+ checks.append(("an exception for a comment that no longer exists is reported stale", len(vanished.stale_exceptions) == 1))++ unexplained = run([ref("a.sh", "docs/nope.md")], accepted={("a.sh", "docs/nope.md"): " "})+ checks.append(("an exception with no reason is reported", len(unexplained.stale_exceptions) == 1))++ # An exception is keyed on (file, token): the same bad path in another+ # file is still a finding, so one excused placeholder cannot licence it+ # everywhere.+ elsewhere = run(+ [ref("a.sh", "docs/nope.md"), ref("b.sh", "docs/nope.md")],+ accepted={("a.sh", "docs/nope.md"): "recorded reason"},+ )+ checks.append(("an exception covers only the file it names", [r.file for r in elsewhere.missing] == ["b.sh"]))++ # --- the readers, not just the rules -----------------------------------+ parsed = comment_text(Path(__file__), ".py")+ checks.append(("the comment reader finds comments in this very file", len(parsed) > 20))+ docs = docstring_text(Path(__file__))+ checks.append(("the docstring reader finds this module's own docstring", any("docker-compose.yml" in line for _, line in docs)))+ checks.append(+ (+ "a URL is recognised by its prefix, not by the token",+ bool(URL_PREFIX_RE.search("see https://github.com/beenuar/AiSOC/blob/main/")) and not URL_PREFIX_RE.search("see "),+ )+ )++ return self_test_main(Path(__file__).name, [], checks)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/eval_telemetry.py b/scripts/eval_telemetry.pyindex 9bcd88100..ebb254f11 100644--- a/scripts/eval_telemetry.py+++ b/scripts/eval_telemetry.py@@ -110,9 +110,9 @@ _SYSTEM_PROMPT_TOKENS = 800# field which mirrors the typical "first-pass context bundle" shape._TELEMETRY_EVENTS_PER_PROMPT = 5-# Completion-budget anchor (tokens). Tuned against the report-template shape-# in ``services/agents/app/investigator/report_template.md`` — a typical-# substrate report at medium severity sits around this length.+# Completion-budget anchor (tokens). Tuned against the report shape+# ``services/agents/app/investigator/report_writer_agent.py`` produces — a+# typical substrate report at medium severity sits around this length._COMPLETION_BASE_TOKENS = 800# Severity scaling for completion length. Higher-severity incidents getdiff --git a/scripts/sync_vendored_llm_contract.py b/scripts/sync_vendored_llm_contract.pyindex de48a5b29..b68a9184d 100755--- a/scripts/sync_vendored_llm_contract.py+++ b/scripts/sync_vendored_llm_contract.py@@ -2,7 +2,7 @@"""Keep ``services/api/app/_vendor/llm_contract_rules.py`` in lockstep with its source.The reversible pseudonymizer lives canonically under-``services/agents/app/privacy/llm_contract_rules.py``. The public-replay publish flow in+``services/agents/app/llm/contract_rules.py``. The public-replay publish flow inthe API service (``services/api/app/services/replay_redaction.py``) reuses it tostrip customer PII before a ledger snapshot is served at ``/r/<slug>``. Becausethe ``aisoc-api`` Docker image is built with ``services/api`` as its builddiff --git a/scripts/validate_detections.py b/scripts/validate_detections.pyindex 08bd92241..5e65081e7 100755--- a/scripts/validate_detections.py+++ b/scripts/validate_detections.py@@ -400,9 +400,9 @@ def main() -> int:for path in yaml_files:rel = path.relative_to(ROOT)- # Skip the meta/index files at the top of detections/, e.g.- # detections/coverage.yaml, that aren't rule files. Those live- # directly under detections/ with no category dir.+ # Skip any meta/index file at the top of detections/ that is not a+ # rule file. A rule lives under a category directory; anything+ # directly under detections/ with no category dir is not one.try:rel_under = path.relative_to(DETECTIONS_DIR)except ValueError:diff --git a/scripts/wet_eval.py b/scripts/wet_eval.pyindex de58ba2d1..82c57faac 100644--- a/scripts/wet_eval.py+++ b/scripts/wet_eval.py@@ -21,10 +21,10 @@ Two modesStdlib-only contract--------------------The dry-run code path is **stdlib-only** so it runs in a bare-Python CI-shell. That's what the workflow's preflight uses to validate the report-shape on every push, and what-``services/agents/tests/test_wet_eval_harness.py`` exercises. Live mode-imports the agent stack lazily and degrades cleanly if it can't.+shell. That's what the ``preflight`` job in+``.github/workflows/wet-eval.yml`` uses to validate the report shape on+every push. Live mode imports the agent stack lazily and degrades cleanly+if it can't.Output shape------------diff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.pyindex a354a531e..54326307c 100644--- a/services/actions/app/live_actions/capabilities.py+++ b/services/actions/app/live_actions/capabilities.py@@ -14,7 +14,7 @@ importing because:Adding a capability:1. Add it to ``Capability`` in ``services/connectors/app/connectors/base.py``.2. Add the same string here.- 3. CI check (``services/actions/tests/test_capability_mirror.py``)+ 3. CI check (``scripts/check_action_contract.py``, ``check_capability_mirror``)compares the two sets and fails the build if they drift.Plugins MAY register executors for capabilities outside this set — wediff --git a/services/agents/app/core/cost_telemetry.py b/services/agents/app/core/cost_telemetry.pyindex 54982aceb..0ce8ccb61 100644--- a/services/agents/app/core/cost_telemetry.py+++ b/services/agents/app/core/cost_telemetry.py@@ -276,11 +276,11 @@ CREATE INDEX IF NOT EXISTS aisoc_run_costs_tenant_runON aisoc_run_costs (tenant_id, run_id);"""-#: Cost provenance, added by ``services/api/migrations/055_cost_provenance.sql``.+#: Cost provenance, added by ``services/api/migrations/063_cost_provenance.sql``.#: Applied here too because this writer has to run against a database whose#: migrations it does not own, and a write that silently drops the provenance#: columns would leave every new row indistinguishable from the pre-provenance-#: rows it exists to separate. Idempotent, and a no-op where 055 already ran.+#: rows it exists to separate. Idempotent, and a no-op where 063 already ran._RUN_COSTS_PROVENANCE_DDL = """ALTER TABLE aisoc_run_costsADD COLUMN IF NOT EXISTS measured_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0,diff --git a/services/agents/app/security/tenant_scope.py b/services/agents/app/security/tenant_scope.pyindex 5e2283a8a..028e86e14 100644--- a/services/agents/app/security/tenant_scope.py+++ b/services/agents/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/services/agents/tests/fidelity/__init__.py b/services/agents/tests/fidelity/__init__.pyindex de2945bc4..6deff72f5 100644--- a/services/agents/tests/fidelity/__init__.py+++ b/services/agents/tests/fidelity/__init__.py@@ -10,7 +10,7 @@ Workspace rule we adhere to: numbers produced by this harness are**substrate** (deterministic, no LLM) unless the runner is invokedwith ``--mode wet``. Substrate numbers are a fidelity floor of theloader-and-rule pipeline; they are not a claim of agent accuracy.-The methodology page (``apps/docs/docs/benchmark-fidelity.md``)+The methodology page (``apps/docs/docs/benchmark-methodology.md``)spells out the substrate-vs-wet distinction in detail.The full datasets are not redistributed in this repo. Seediff --git a/services/agents/tests/fidelity/expected_results.yaml b/services/agents/tests/fidelity/expected_results.yamlindex 9d4a67f08..2e5f038c3 100644--- a/services/agents/tests/fidelity/expected_results.yaml+++ b/services/agents/tests/fidelity/expected_results.yaml@@ -2,8 +2,8 @@## These thresholds gate the substrate harness in CI. They are NOT a# claim about live agent (wet) accuracy on these datasets — see-# apps/docs/docs/benchmark-fidelity.md for the substrate-vs-wet-# distinction. Wet numbers are produced manually and copied into+# apps/docs/docs/benchmark-methodology.md (§3, "Substrate vs. wet eval")+# for the distinction. Wet numbers are produced manually and copied into# apps/docs/docs/benchmark.md.## Methodology:diff --git a/services/agents/tests/test_llm_resolver.py b/services/agents/tests/test_llm_resolver.pyindex 92c14458c..c3a3315d5 100644--- a/services/agents/tests/test_llm_resolver.py+++ b/services/agents/tests/test_llm_resolver.py@@ -114,7 +114,7 @@ def _reset_state(monkeypatch: pytest.MonkeyPatch) -> None:class TestEnvBaseline:"""Verify the resolver speaks the same env-var dialect as the API- service's status endpoint (``services/api/.../llm_status.py``).+ service's status endpoint (``services/api/app/api/v1/endpoints/llm_status.py``)."""def test_empty_env_returns_blank_triple(self) -> None:diff --git a/services/agents/tests/test_response_quality.py b/services/agents/tests/test_response_quality.pyindex 2c31f494f..2d6e18de1 100644--- a/services/agents/tests/test_response_quality.py+++ b/services/agents/tests/test_response_quality.py@@ -34,8 +34,8 @@ regression floor, AND per-template macro mean ≥ 0.75 across the ~55distinct templates. The per-template gate is the regression-signal-preserving metric: with ~3-4 duplicates per template, a single brokentemplate moves per-case mean by ~0.5% but per-template mean by ~1.5%-(addressing the dilution concern raised in-`docs/research/dataset-design-notes.md`).+(addressing the dilution concern that duplicate templates would otherwise+hide a single broken one).See `apps/docs/docs/benchmark.md` for what each suite actually measures.diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex c161febff..e059a3646 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -96,7 +96,7 @@ api_router.include_router(alert_explain.router)api_router.include_router(alert_writeback.router)api_router.include_router(cases.router)# Attack-chain timeline (T3.3 — v8.0 parallel team plan).-# Backs apps/web/src/app/(app)/cases/[id]/attack-chain/page.tsx with a+# Backs the attack-chain view in apps/web/src/components/cases/CaseWorkspace.tsx with a# ranked timeline (graph-distance + temporal proximity + risk overlap)# of every alert that shares an entity with the case's seed alert,# plus the side-by-side entity graph the right column renders.diff --git a/services/api/app/workers/_tick_failures.py b/services/api/app/workers/_tick_failures.pynew file mode 100644index 000000000..432b5a1da--- /dev/null+++ b/services/api/app/workers/_tick_failures.py@@ -0,0 +1,103 @@+"""Report a failing scheduler tick in a way an operator can act on.++Both long-running tick loops in this package used to log ``err=%s`` with+``type(exc).__name__`` and nothing else. That is louder than silence and not+much more useful: ``err=ProgrammingError`` repeated every thirty seconds says+a tick failed, never *why*, and — the part that costs an incident —+never whether waiting is the right response.++The distinction matters because these loops cannot tell the two apart by+construction. A ``ProgrammingError`` from a column the migration never+created will fail identically on every future tick; an ``OperationalError``+from a database that is restarting will clear on the next one. Printing the+same line for both makes a permanent misconfiguration read as ordinary churn,+which is the failure mode the UEBA consumer shipped with and the playbook+bridge was split in two to avoid.++So a tracker counts consecutive failures, keeps the message, and escalates+once the run has outlived any explanation a retry would fix. It does not+classify exception types: doing that here would need a SQLAlchemy import in+a module two loops share for logging, and the elapsed-time signal answers the+operator's actual question — "is this still worth waiting on" — without+guessing.++Messages are sanitised inline at the call site rather than through a helper,+because CodeQL's taint tracker does not follow a sanitiser across a function+boundary but does recognise the inline ``replace``/slice chain. See+``apps/docs/docs/operations/security.md#static-analysis-codeql``.+"""++from __future__ import annotations++import logging+import time+++class TickFailures:+ """Consecutive-failure state for one tick loop.++ Not thread-safe and does not need to be: each instance belongs to a+ single asyncio task that owns its loop.+ """++ def __init__(self, name: str, logger: logging.Logger, *, stuck_after_seconds: float = 300.0) -> None:+ self._name = name+ self._log = logger+ self._stuck_after = stuck_after_seconds+ self._consecutive = 0+ self._since = 0.0++ @property+ def consecutive(self) -> int:+ return self._consecutive++ @property+ def not_resolving(self) -> bool:+ """Whether this run of failures has outlived a transient explanation."""+ return self._consecutive > 0 and (time.monotonic() - self._since) >= self._stuck_after++ def record_failure(self, exc: BaseException) -> None:+ """Log one failed tick at a level that matches what can be done about it."""+ now = time.monotonic()+ if self._consecutive == 0:+ self._since = now+ self._consecutive += 1+ elapsed = now - self._since++ # Inline sanitisation, deliberately not extracted (see module docstring).+ detail = str(exc).replace("\r", "").replace("\n", " ")[:300]++ if self.not_resolving:+ self._log.error(+ "%s tick failing for %.0fs across %d consecutive attempts; "+ "treat this as a misconfiguration rather than churn err=%s detail=%s",+ self._name,+ elapsed,+ self._consecutive,+ type(exc).__name__,+ detail,+ )+ else:+ self._log.warning(+ "%s tick failed (attempt %d) err=%s detail=%s",+ self._name,+ self._consecutive,+ type(exc).__name__,+ detail,+ )++ def record_success(self) -> None:+ """Clear the run, and say so if there was one.++ A recovery that is not logged leaves the last line in the log+ describing a fault that has since cleared.+ """+ if self._consecutive:+ self._log.info(+ "%s recovered after %d consecutive failure(s) over %.0fs",+ self._name,+ self._consecutive,+ time.monotonic() - self._since,+ )+ self._consecutive = 0+ self._since = 0.0diff --git a/services/api/app/workers/hunt_scheduler.py b/services/api/app/workers/hunt_scheduler.pyindex cda88601a..aacfd1707 100644--- a/services/api/app/workers/hunt_scheduler.py+++ b/services/api/app/workers/hunt_scheduler.py@@ -80,6 +80,7 @@ from app.services.event_warehouse import (resolve_provider,resolve_tenant_warehouse,)+from app.workers._tick_failures import TickFailurestry:from croniter import croniter # type: ignore[import-untyped]@@ -465,6 +466,7 @@ async def run_forever() -> None:"""Tick the scheduler until cancelled. Owned by the API ``lifespan``."""interval = max(int(getattr(settings, "HUNT_SCHEDULER_POLL_INTERVAL_SECONDS", 30)), 5)logger.info("hunt_scheduler started interval=%ds", interval)+ failures = TickFailures("hunt_scheduler", logger)try:while True:try:@@ -474,10 +476,9 @@ async def run_forever() -> None:except asyncio.CancelledError:raiseexcept Exception as exc: # pragma: no cover - defensive- logger.warning(- "hunt_scheduler tick failed err=%s",- type(exc).__name__,- )+ failures.record_failure(exc)+ else:+ failures.record_success()await asyncio.sleep(interval)except asyncio.CancelledError:logger.info("hunt_scheduler stopped")diff --git a/services/api/app/workers/retention_purge.py b/services/api/app/workers/retention_purge.pyindex ffd39097f..be0b7ec02 100644--- a/services/api/app/workers/retention_purge.py+++ b/services/api/app/workers/retention_purge.py@@ -49,6 +49,7 @@ from app.db.clickhouse import execute_lake_queryfrom app.db.cross_tenant import assert_cross_tenant_sessionfrom app.db.database import AsyncSessionLocalfrom app.services.retention import _clamp, build_lake_purge_sql, resolve_policy+from app.workers._tick_failures import TickFailureslogger = logging.getLogger("aisoc.retention_purge")@@ -268,6 +269,7 @@ async def run_forever() -> None:"retention_purge is in dry-run: policies are evaluated and the row counts ""logged, but nothing is deleted. Set RETENTION_WORKER_DRY_RUN=false to arm it.")+ failures = TickFailures("retention_purge", logger)try:while True:try:@@ -275,7 +277,9 @@ async def run_forever() -> None:except asyncio.CancelledError:raiseexcept Exception as exc: # pragma: no cover - defensive- logger.warning("retention_purge tick failed err=%s", type(exc).__name__)+ failures.record_failure(exc)+ else:+ failures.record_success()await asyncio.sleep(interval)except asyncio.CancelledError:logger.info("retention_purge stopped")diff --git a/services/api/tests/api/v1/endpoints/test_realtime_ticket.py b/services/api/tests/api/v1/endpoints/test_realtime_ticket.pyindex 321aba408..40a745889 100644--- a/services/api/tests/api/v1/endpoints/test_realtime_ticket.py+++ b/services/api/tests/api/v1/endpoints/test_realtime_ticket.py@@ -17,7 +17,7 @@ These tests pin the API half of that contract so it cannot silently regress:shared secret is unconfigured in prod.The Node-side signature/aud/exp verification is pinned separately in-``services/realtime/src/auth.test.ts``. The claim shape here must stay in sync+``services/realtime/test/auth.test.ts``. The claim shape here must stay in syncwith ``RealtimeClaims`` / ``verifyRealtimeTicket`` there.AiSOC — open-source AI Security Operations Center (MIT License)diff --git a/services/api/tests/test_tick_failures.py b/services/api/tests/test_tick_failures.pynew file mode 100644index 000000000..ea077df46--- /dev/null+++ b/services/api/tests/test_tick_failures.py@@ -0,0 +1,84 @@+"""A failing tick has to say what failed, and whether waiting will help.++Both scheduler loops in ``app/workers`` logged ``err=<ExceptionTypeName>``+and nothing else. ``err=ProgrammingError`` every thirty seconds is a line+that repeats forever without ever telling an operator whether their next+move is to wait or to go and fix something — the same shape as a consumer+that retries a permanent failure in silence, one level quieter.+"""++from __future__ import annotations++import logging++import pytest+from app.workers._tick_failures import TickFailures+++def logger() -> logging.Logger:+ return logging.getLogger("aisoc.test.tick_failures")+++def test_the_first_failure_is_a_warning_that_carries_the_message(caplog, logger):+ tracker = TickFailures("demo", logger)+ with caplog.at_level(logging.WARNING, logger=logger.name):+ tracker.record_failure(RuntimeError('column "peer_group_id" does not exist'))++ record = caplog.records[-1]+ assert record.levelno == logging.WARNING+ assert "peer_group_id" in record.getMessage(), "the message is what makes the line actionable"+ assert "RuntimeError" in record.getMessage()+++def test_a_run_that_outlives_a_transient_explanation_escalates(caplog, logger):+ tracker = TickFailures("demo", logger, stuck_after_seconds=0.0)+ with caplog.at_level(logging.WARNING, logger=logger.name):+ tracker.record_failure(RuntimeError("boom"))++ record = caplog.records[-1]+ assert record.levelno == logging.ERROR+ assert "misconfiguration rather than churn" in record.getMessage()+++def test_a_short_run_is_not_called_not_resolving(logger):+ tracker = TickFailures("demo", logger, stuck_after_seconds=3600.0)+ tracker.record_failure(RuntimeError("boom"))+ assert not tracker.not_resolving, "a single failure is exactly what a retry is for"+ assert tracker.consecutive == 1+++def test_recovery_is_logged_so_the_last_line_is_not_a_stale_fault(caplog, logger):+ tracker = TickFailures("demo", logger, stuck_after_seconds=0.0)+ tracker.record_failure(RuntimeError("boom"))+ with caplog.at_level(logging.INFO, logger=logger.name):+ tracker.record_success()++ assert "recovered after 1 consecutive failure" in caplog.records[-1].getMessage()+ assert tracker.consecutive == 0+ assert not tracker.not_resolving+++def test_a_success_with_no_prior_failure_says_nothing(caplog, logger):+ tracker = TickFailures("demo", logger)+ with caplog.at_level(logging.INFO, logger=logger.name):+ tracker.record_success()+ assert caplog.records == [], "a healthy loop must not narrate every tick"+++def test_newlines_in_the_message_cannot_forge_a_log_line(caplog, logger):+ tracker = TickFailures("demo", logger)+ with caplog.at_level(logging.WARNING, logger=logger.name):+ tracker.record_failure(RuntimeError("real failure\nWARNING fake line injected"))++ rendered = caplog.records[-1].getMessage()+ assert "\n" not in rendered+ assert "\r" not in rendered+ assert "fake line injected" in rendered, "the text is kept, only the line break is removed"+++def test_a_long_message_is_truncated(caplog, logger):+ tracker = TickFailures("demo", logger)+ with caplog.at_level(logging.WARNING, logger=logger.name):+ tracker.record_failure(RuntimeError("x" * 5000))+ assert len(caplog.records[-1].getMessage()) < 600diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.pyindex 68c8590e0..3f8f5c6ed 100644--- a/services/connectors/app/connectors/base.py+++ b/services/connectors/app/connectors/base.py@@ -40,7 +40,8 @@ if TYPE_CHECKING:# CONTAIN / REMEDIATE / TICKET / AUDIT). Adding a new capability:# 1. Add the enum member here.# 2. Update the relevant connectors' ``capabilities()`` classmethod.-# 3. Update ``test_capabilities`` in ``services/connectors/tests/test_capabilities.py``.+# 3. Keep ``test_every_declared_capability_is_a_valid_verb`` in+# ``services/connectors/tests/test_conformance.py`` passing.## Per-instance downscoping happens in the API layer: an operator can store an# ``allowed_capabilities`` whitelist on a ``Connector`` row and the agentdiff --git a/services/connectors/app/connectors/wazuh.py b/services/connectors/app/connectors/wazuh.pyindex b560c36a2..4a89e27ce 100644--- a/services/connectors/app/connectors/wazuh.py+++ b/services/connectors/app/connectors/wazuh.py@@ -67,7 +67,7 @@ logger = structlog.get_logger()# ``info | low | medium | high | critical`` ladder. Level 15 is the only# tier Wazuh explicitly documents as "critical / attack" so we surface it# at the AiSOC ``critical`` band; levels 12-14 stay at ``high``. The-# matching operator-facing table lives in ``apps/docs/connectors/wazuh.md``+# matching operator-facing table lives in ``apps/docs/docs/connectors/wazuh.md``# so SOC analysts can predict what they will see. Boundaries are inclusive# on the lower end.# ---------------------------------------------------------------------------diff --git a/services/connectors/app/security/tenant_scope.py b/services/connectors/app/security/tenant_scope.pyindex 386283466..28a4a76fb 100644--- a/services/connectors/app/security/tenant_scope.py+++ b/services/connectors/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/services/demo-producer/main.go b/services/demo-producer/main.goindex c002381ea..1ccd71782 100644--- a/services/demo-producer/main.go+++ b/services/demo-producer/main.go@@ -233,7 +233,14 @@ func runProducer(ctx context.Context, wg *sync.WaitGroup, profile connectorProfi}req, err := http.NewRequestWithContext(ctx, "POST", opts.ingestURL, bytes.NewReader(body))if err != nil {- continue+ // A malformed URL never becomes a well-formed one, so this+ // is the one error in this loop that retrying cannot clear.+ // Silently continuing produced a producer that ticked+ // forever and sent nothing, which is the shape this loop+ // must never have again.+ fmt.Fprintf(os.Stderr, "[%s] cannot build a request for %q: %v — this will not resolve; fix --ingest-url\n",+ profile.id, opts.ingestURL, err)+ return}req.Header.Set("Content-Type", "application/json")req.Header.Set("X-Tenant-ID", opts.tenant)diff --git a/services/fusion/app/security/tenant_scope.py b/services/fusion/app/security/tenant_scope.pyindex 2ad208bca..567a5e1de 100644--- a/services/fusion/app/security/tenant_scope.py+++ b/services/fusion/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/services/honeytokens/app/security/service_auth.py b/services/honeytokens/app/security/service_auth.pyindex 8105371df..450a73dd2 100644--- a/services/honeytokens/app/security/service_auth.py+++ b/services/honeytokens/app/security/service_auth.py@@ -31,7 +31,7 @@ ConfigurationWhen set and no token is configured, requests are allowed through so alocal ``docker compose up`` still works. This mirrors the single canonicaldev-mode flag used across the platform; it is asserted off in production by- ``tests/test_security_defaults.py``.+ ``services/api/tests/test_security_defaults.py``."""from __future__ import annotationsdiff --git a/services/honeytokens/app/security/tenant_scope.py b/services/honeytokens/app/security/tenant_scope.pyindex 832947218..fe2084ad6 100644--- a/services/honeytokens/app/security/tenant_scope.py+++ b/services/honeytokens/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/services/ingest/internal/graph_ws/broadcaster.go b/services/ingest/internal/graph_ws/broadcaster.goindex ad36d5f02..428db38c0 100644--- a/services/ingest/internal/graph_ws/broadcaster.go+++ b/services/ingest/internal/graph_ws/broadcaster.go@@ -81,6 +81,10 @@ type Broadcaster struct {dropped atomic.Uint64+ // health is shared with the source, so an error the Kafka reader+ // swallows internally and an error the loop sees land in one place.+ health *SourceState+stopCh chan struct{}doneCh chan struct{}}@@ -90,6 +94,20 @@ type Options struct {// BufferSize overrides subscriberBufferDefault. Zero falls back// to the default; negative is rejected at construction.BufferSize int++ // Health is the failure state shared with the EnvelopeSource. Pass the+ // same *SourceState given to NewKafkaSource so the reader's internal+ // dial and rebalance failures are counted alongside the loop's. Nil+ // creates a private one, which is the right default for a fake source+ // in a test.+ Health *SourceState++ // Topic names the subscription in logs and metrics when Health is nil.+ Topic string++ // StuckAfter overrides how long a transient failure may persist before+ // it is reported as not resolving. Only consulted when Health is nil.+ StuckAfter time.Duration}// New constructs a broadcaster wired to src. Call Start to begin@@ -99,15 +117,30 @@ func New(src EnvelopeSource, opts Options) *Broadcaster {if buf <= 0 {buf = subscriberBufferDefault}+ health := opts.Health+ if health == nil {+ health = NewSourceState(opts.Topic, opts.StuckAfter)+ }return &Broadcaster{src: src,subscribers: make(map[uint64]*Subscriber),bufferSize: buf,+ health: health,stopCh: make(chan struct{}),doneCh: make(chan struct{}),}}+// Health reports the state of the subscription: attached or not, how long it+// has been failing, and whether the failure is one a retry can clear.+//+// Read by the /readyz probe and by the WebSocket upgrade handler, which+// refuses a connection it could not serve rather than completing a handshake+// onto a socket that will stay silent.+func (b *Broadcaster) Health() SourceHealth {+ return b.health.Health()+}+// Start launches the consumer goroutine. It returns immediately; the// goroutine runs until ctx is cancelled or Stop is called. Calling// Start more than once is a programmer error.@@ -204,8 +237,28 @@ func (b *Broadcaster) DroppedDeliveries() uint64 {return b.dropped.Load()}+// consumeLoop pulls envelopes from the source and fans them out.+//+// What it used to do with an error was `continue` after a flat 50ms, with+// the error discarded. The loop survived, which is why this was not the+// UEBA defect — but a broker that was never coming back produced twenty+// silent reconnects a second behind a container reporting healthy, which is+// the same thing an operator cannot see. Every error now lands in+// SourceState: classified, counted, logged at a level that matches what can+// be done about it, and backed off in proportion to how long it has lasted.+//+// A permanent failure ends the loop rather than retrying it. That follows+// the UEBA consumer's reasoning: a loop over a fault no retry can clear+// turns a misconfiguration into indefinite churn, and churn reads as+// ordinary. The honest report is the error in the log, the detached state on+// /readyz, and a 503 from the WebSocket route — not a reconnect counter+// climbing forever.func (b *Broadcaster) consumeLoop(ctx context.Context) {defer close(b.doneCh)+ b.health.MarkAttached()+ reason := "stopped"+ defer func() { b.health.MarkDetached(reason) }()+for {select {case <-ctx.Done():@@ -216,16 +269,23 @@ func (b *Broadcaster) consumeLoop(ctx context.Context) {}env, err := b.src.Next(ctx)if err != nil {- if ctx.Err() != nil {+ // A cancelled context is the operator stopping the service. It+ // is not a fault and must not be counted as one, or every clean+ // shutdown would leave a failure as the last thing recorded.+ if ctx.Err() != nil || isContextError(err) {+ return+ }+ class, wait := b.health.RecordFailure(err)+ if class == ClassPermanent {+ reason = "permanent source failure: " + err.Error()return}- select {- case <-b.stopCh:+ if !sleepFor(ctx, b.stopCh, wait) {return- case <-time.After(50 * time.Millisecond):}continue}+ b.health.RecordMessage()b.dispatch(env)}}diff --git a/services/ingest/internal/graph_ws/kafka_source.go b/services/ingest/internal/graph_ws/kafka_source.goindex 9ca479bcc..d77d5a4b2 100644--- a/services/ingest/internal/graph_ws/kafka_source.go+++ b/services/ingest/internal/graph_ws/kafka_source.go@@ -30,6 +30,15 @@ type KafkaSourceConfig struct {// kafka.FirstOffset or kafka.LastOffset; defaults to LastOffset// because the WS contract is "live tail, no replay".StartOffset int64++ // Health receives every failure this source notices, including the+ // ones kafka-go reports to its own error logger instead of returning+ // from ReadMessage. Pass the same *SourceState to graph_ws.New so the+ // loop and the reader agree about the state of the subscription.+ //+ // Nil is allowed and still logs — a source whose errors go nowhere is+ // the defect this exists to close — but the counters are dropped.+ Health *SourceState}// KafkaSource is the production EnvelopeSource. It owns a kafka.Reader@@ -59,13 +68,27 @@ func NewKafkaSource(cfg KafkaSourceConfig) (*KafkaSource, error) {if start == 0 {start = kafka.LastOffset}+ brokers := splitCSV(cfg.Brokers)+ if len(brokers) == 0 {+ return nil, fmt.Errorf("graph_ws: kafka brokers required")+ }rd := kafka.NewReader(kafka.ReaderConfig{- Brokers: splitCSV(cfg.Brokers),+ Brokers: brokers,Topic: cfg.Topic,GroupID: group,StartOffset: start,MinBytes: 1,MaxBytes: 10 * 1024 * 1024,+ // Without this the reader falls back to a silent logger (reader.go+ // `withErrorLogger`), and with a GroupID set that is where every+ // dial, join, and rebalance failure goes — ReadMessage stays+ // blocked and returns nothing. So the single most likely permanent+ // fault, a broker that is unreachable or misnamed, was discarded+ // inside the library before this package could see it. An+ // unreachable broker now says so.+ ErrorLogger: kafka.LoggerFunc(func(format string, args ...interface{}) {+ cfg.Health.ObserveReaderError(fmt.Sprintf(format, args...))+ }),})return &KafkaSource{reader: rd}, nil}@@ -78,7 +101,11 @@ func (k *KafkaSource) Next(ctx context.Context) (graph.GraphUpdate, error) {}var env graph.GraphUpdateif err := json.Unmarshal(msg.Value, &env); err != nil {- return graph.GraphUpdate{}, fmt.Errorf("graph_ws: decode envelope: %w", err)+ // Poison, not a source failure: this envelope is unreadable and the+ // next one may be fine. Backing the subscription off for a malformed+ // message would report a broken topic where there is a broken+ // producer.+ return graph.GraphUpdate{}, Poison(fmt.Errorf("graph_ws: decode envelope: %w", err))}if env.TenantID == "" {for _, h := range msg.Headers {diff --git a/services/ingest/internal/graph_ws/server.go b/services/ingest/internal/graph_ws/server.goindex b9eb08b7b..5b6674774 100644--- a/services/ingest/internal/graph_ws/server.go+++ b/services/ingest/internal/graph_ws/server.go@@ -77,6 +77,19 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) {return}+ // Refuse rather than complete a handshake onto a socket that will stay+ // silent. A client connected to a broadcaster whose source is detached+ // gets an open connection and no envelopes, which looks exactly like a+ // quiet estate — the same indistinguishability that made the consumer+ // defect invisible in the first place. The endpoint that depends on the+ // subscription is the right place to report on it, and 503 with the+ // reason lets a caller retry or escalate instead of waiting forever.+ if health := s.broker.Health(); !health.Healthy() {+ w.Header().Set("Retry-After", "30")+ http.Error(w, "graph_ws unavailable: "+health.Reason(), http.StatusServiceUnavailable)+ return+ }+hj, ok := w.(http.Hijacker)if !ok {http.Error(w, "websocket not supported", http.StatusInternalServerError)@@ -284,9 +297,16 @@ var (// String returns a one-line summary of broadcaster state. Used by// the `/internal/graph_ws/stats` debug endpoint.+//+// Source state is included because subscriber and drop counts describe the+// fan-out only: both read identically whether the topic is quiet or the+// consumer is detached from it.func (s *Server) String() string {- return fmt.Sprintf("graph_ws: subscribers=%d dropped=%d",+ health := s.broker.Health()+ return fmt.Sprintf("graph_ws: subscribers=%d dropped=%d attached=%t not_resolving=%t",s.broker.SubscriberCount(),s.broker.DroppedDeliveries(),+ health.Attached,+ health.NotResolving,)}diff --git a/services/ingest/internal/graph_ws/source_health.go b/services/ingest/internal/graph_ws/source_health.gonew file mode 100644index 000000000..1b829baa7--- /dev/null+++ b/services/ingest/internal/graph_ws/source_health.go@@ -0,0 +1,641 @@+// Failure classification and reporting for the graph_ws envelope source.+//+// Why this file exists+// --------------------+// The consume loop answered every source error the same way: a 50ms sleep+// and `continue`, with the error discarded. It could not die the way the+// UEBA consumer did — the loop survives — but it could do something no+// better. A broker that is never coming back produced a healthy container,+// restarts 0, /health 200, and a WebSocket that delivered nothing, with no+// line in any log and no counter anywhere. That is the same defect as a+// silent death: a permanent failure wearing the costume of a transient one.+//+// Worse, most of those errors never even reached the loop.+// `kafka.NewReader` falls back to a silent logger when `ErrorLogger` is nil+// (see reader.go `withErrorLogger`), and with a GroupID set the consumer+// group's dial, join, and rebalance failures are reported *only* through+// that logger — `ReadMessage` stays blocked. So the single most likely+// permanent fault, an unreachable or misnamed broker, was discarded inside+// the library before this package ever saw it. `NewKafkaSource` now wires+// `ErrorLogger` here.+//+// The three answers a loop can give+// ---------------------------------+// The question this file exists to answer is the one the repository already+// asked of the playbook bridge, where `BridgeUnavailable` was split into a+// permanent and a transient half: *can this loop distinguish a condition+// that will never resolve from one that might, and does it say so?*+//+// transient retrying can clear it — a broker restarting, a rebalance,+// a leader election. Back off and retry, quietly at first.+// permanent retrying cannot. The Kafka protocol's own error table says+// so (`kafka.Error.Temporary()` is the retriable set), or the+// configuration is wrong. Say so at error level with the+// operator action, and stop pretending a retry is progress.+// poison one message is unreadable. The subscription is fine; the+// envelope is not. Count it, log it, take the next message —+// do not back off, because nothing is wrong with the source.+//+// A fourth state is not a class but a duration. A `no such host` on a+// broker name can genuinely be a startup race for a few seconds, and can+// equally be a variable nobody set. Guessing either way is wrong, so the+// loop reports the first as transient and then escalates once the condition+// has outlived any plausible transient explanation: after `StuckAfter` the+// same failure is reported as *not resolving*, which is the point at which+// the operator's next move stops being "wait" and becomes "go and look".+package graph_ws++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "sync"+ "time"++ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/promauto"+ "github.com/rs/zerolog/log"+ kafka "github.com/segmentio/kafka-go"+)++// FailureClass is what the consume loop can do about an error, which is the+// only distinction that changes its behaviour.+type FailureClass string++const (+ // ClassTransient — a retry can clear it.+ ClassTransient FailureClass = "transient"+ // ClassPermanent — a retry cannot. Needs an operator.+ ClassPermanent FailureClass = "permanent"+ // ClassPoison — this message is unreadable; the subscription is healthy.+ ClassPoison FailureClass = "poison"+)++// DefaultStuckAfter is how long a transient failure may persist before it is+// reported as not resolving. Two minutes is longer than a broker restart, a+// leader election, or a Kubernetes service coming up behind its DNS record,+// and far shorter than the "forever" the previous code implied.+const DefaultStuckAfter = 2 * time.Minute++// repeatEvery bounds how often a failure that keeps happening is re-logged.+// The first occurrence is always logged; the cap is what stops a 50ms retry+// loop turning a real signal into a log flood that hides it.+const repeatEvery = 30 * time.Second++// Backoff bounds. The old loop used a flat 50ms, which against an+// unreachable broker is twenty reconnect attempts a second, forever.+const (+ backoffMin = 50 * time.Millisecond+ backoffMax = 30 * time.Second+)++var (+ sourceAttached = promauto.NewGaugeVec(prometheus.GaugeOpts{+ Name: "aisoc_graph_ws_source_attached",+ Help: "1 when the graph_ws broadcaster is consuming its topic, 0 when it is not.",+ }, []string{"topic"})++ sourceErrors = promauto.NewCounterVec(prometheus.CounterOpts{+ Name: "aisoc_graph_ws_source_errors_total",+ Help: "Errors from the graph_ws envelope source, by class (transient, permanent, poison).",+ }, []string{"topic", "class"})++ sourceStuck = promauto.NewGaugeVec(prometheus.GaugeOpts{+ Name: "aisoc_graph_ws_source_not_resolving",+ Help: "1 when the graph_ws source has been failing for longer than a transient fault explains.",+ }, []string{"topic"})+)++// permanentError marks an error the loop must not treat as retriable, and+// carries the action that would actually fix it.+type permanentError struct {+ err error+ advice string+}++func (e *permanentError) Error() string { return e.err.Error() }+func (e *permanentError) Unwrap() error { return e.err }++// Permanent wraps err so the consume loop stops retrying and reports advice+// as the operator's next move. A source implementation calls this when it+// knows retrying is futile.+func Permanent(err error, advice string) error {+ if err == nil {+ return nil+ }+ return &permanentError{err: err, advice: advice}+}++// poisonError marks an error that is about one message rather than about the+// subscription.+type poisonError struct{ err error }++func (e *poisonError) Error() string { return e.err.Error() }+func (e *poisonError) Unwrap() error { return e.err }++// Poison wraps err so the loop skips this message without backing off or+// treating the source as unhealthy.+func Poison(err error) error {+ if err == nil {+ return nil+ }+ return &poisonError{err: err}+}++// permanentProtocolErrors are the Kafka error codes where no number of+// retries by this client changes the answer: the broker has refused this+// principal, cannot speak to this client, or was handed a name it will never+// accept. Each needs a person.+//+// Enumerated rather than derived from `kafka.Error.Temporary()`, which is+// upstream's transcription of the protocol's "retriable" column and answers+// a subtly different question. `RebalanceInProgress` is not retriable in+// that sense — the client is meant to rejoin, not resend — but it is a+// routine event during every deploy, and stopping the consumer on it would+// turn this fix into an outage. `UnknownTopicOrPartition` is likewise+// retriable in the table and genuinely clears when the topic is created.+// Deciding by negation would have got both wrong; TestClassifyCreditsOnly...+// walks the whole table so that stays true as the table grows.+var permanentProtocolErrors = map[kafka.Error]string{+ kafka.TopicAuthorizationFailed: "grant this client read on the topic, or point it at one it may read",+ kafka.GroupAuthorizationFailed: "grant this client access to the consumer group, or change AISOC_GRAPH_WS_GROUP_ID",+ kafka.ClusterAuthorizationFailed: "the broker refused this principal; check the credentials this service runs with",+ kafka.SASLAuthenticationFailed: "the broker rejected these credentials; they will not start working on their own",+ kafka.UnsupportedSASLMechanism: "the broker does not offer this SASL mechanism; reconfigure the client",+ kafka.IllegalSASLState: "the SASL handshake was attempted out of order; this is a client configuration fault",+ kafka.UnsupportedVersion: "this client and this broker cannot agree on a protocol version",+ kafka.InvalidTopic: "the topic name is not valid; check AISOC_GRAPH_UPDATES_TOPIC",+ kafka.InvalidGroupId: "the consumer group id is not valid; check AISOC_GRAPH_WS_GROUP_ID",+ kafka.SecurityDisabled: "the broker has security disabled and cannot answer this request",+}++// classify answers the only question the loop needs: what can be done about+// this error, and what should an operator be told.+//+// Advice is returned for transient errors too when there is a known remedy.+// An absent topic is retriable — it appears the moment somebody creates it —+// but telling the operator that is the difference between a log line they+// can act on and one they can only watch.+func classify(err error) (FailureClass, string) {+ if err == nil {+ return ClassTransient, ""+ }++ var poison *poisonError+ if errors.As(err, &poison) {+ return ClassPoison, "the envelope could not be decoded; the subscription is unaffected"+ }++ var permanent *permanentError+ if errors.As(err, &permanent) {+ return ClassPermanent, permanent.advice+ }++ var advised *advisedError+ if errors.As(err, &advised) {+ return ClassTransient, advised.advice+ }++ var kerr kafka.Error+ if errors.As(err, &kerr) {+ if advice, ok := permanentProtocolErrors[kerr]; ok {+ return ClassPermanent, advice+ }+ if kerr == kafka.UnknownTopicOrPartition {+ return ClassTransient, "create the topic, or enable auto-creation on the broker"+ }+ return ClassTransient, ""+ }++ // A JSON decode reaching here unwrapped is still about one message.+ var syntax *json.SyntaxError+ var unmarshal *json.UnmarshalTypeError+ if errors.As(err, &syntax) || errors.As(err, &unmarshal) {+ return ClassPoison, "the envelope could not be decoded; the subscription is unaffected"+ }++ // Everything else — dial failures, EOF, timeouts, a broker mid-restart —+ // is transient by default, because assuming otherwise would stop a loop+ // that a retry really would have fixed. What keeps that default honest+ // is the elapsed-time escalation in SourceState: a transient failure+ // that outlives DefaultStuckAfter is reported as not resolving.+ return ClassTransient, ""+}++// SourceState is everything the loop, the readiness probe, and the WebSocket+// upgrade handler know about the subscription. One object shared by the+// source and the broadcaster, so the errors the Kafka reader notices on its+// own land in the same place as the ones the loop sees.+//+// Safe for concurrent use.+type SourceState struct {+ topic string+ stuckAfter time.Duration++ mu sync.Mutex+ attached bool+ permanent bool+ permanentAdvice string+ consecutive uint64+ transientFailures uint64+ permanentFailures uint64+ poisonMessages uint64+ failingSince time.Time+ lastError string+ lastAdvice string+ lastClass FailureClass+ lastMessageAt time.Time+ everReceived bool+ lastLoggedAt time.Time+ lastLoggedSignature string+}++// NewSourceState builds the shared state for a subscription to topic.+// stuckAfter of zero means DefaultStuckAfter.+func NewSourceState(topic string, stuckAfter time.Duration) *SourceState {+ if stuckAfter <= 0 {+ stuckAfter = DefaultStuckAfter+ }+ if topic == "" {+ topic = "unknown"+ }+ sourceAttached.WithLabelValues(topic).Set(0)+ sourceStuck.WithLabelValues(topic).Set(0)+ return &SourceState{topic: topic, stuckAfter: stuckAfter}+}++// SourceHealth is a point-in-time copy, safe to serialise.+type SourceHealth struct {+ Topic string `json:"topic"`+ Attached bool `json:"attached"`+ NotResolving bool `json:"not_resolving"`+ PermanentFailure bool `json:"permanent_failure"`+ Advice string `json:"advice,omitempty"`+ ConsecutiveFailures uint64 `json:"consecutive_failures"`+ TransientFailures uint64 `json:"transient_failures"`+ PermanentFailures uint64 `json:"permanent_failures"`+ PoisonMessages uint64 `json:"poison_messages"`+ FailingForSeconds float64 `json:"failing_for_seconds,omitempty"`+ LastError string `json:"last_error,omitempty"`+ LastErrorClass FailureClass `json:"last_error_class,omitempty"`+ EverReceived bool `json:"ever_received"`+ SinceLastMessage time.Duration `json:"-"`+}++// Healthy is the one-line verdict the WebSocket handler and the readiness+// probe branch on: the loop is attached and is not sitting on a fault that+// has outlived a transient explanation.+func (h SourceHealth) Healthy() bool {+ return h.Attached && !h.NotResolving && !h.PermanentFailure+}++// Reason is a human sentence for the current state, or "" when healthy.+func (h SourceHealth) Reason() string {+ switch {+ case h.PermanentFailure:+ return fmt.Sprintf("permanent source failure on %s: %s (%s)", h.Topic, h.LastError, h.Advice)+ case !h.Attached:+ return fmt.Sprintf("not consuming %s", h.Topic)+ case h.NotResolving:+ reason := fmt.Sprintf("source for %s has been failing for %.0fs (%d consecutive): %s",+ h.Topic, h.FailingForSeconds, h.ConsecutiveFailures, h.LastError)+ if h.Advice != "" {+ reason += " — " + h.Advice+ }+ return reason+ default:+ return ""+ }+}++func firstNonEmpty(values ...string) string {+ for _, v := range values {+ if v != "" {+ return v+ }+ }+ return ""+}++// Health returns a copy of the current state.+func (s *SourceState) Health() SourceHealth {+ if s == nil {+ return SourceHealth{}+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ h := SourceHealth{+ Topic: s.topic,+ Attached: s.attached,+ NotResolving: s.notResolvingLocked(),+ PermanentFailure: s.permanent,+ Advice: firstNonEmpty(s.permanentAdvice, s.lastAdvice),+ ConsecutiveFailures: s.consecutive,+ TransientFailures: s.transientFailures,+ PermanentFailures: s.permanentFailures,+ PoisonMessages: s.poisonMessages,+ LastError: s.lastError,+ LastErrorClass: s.lastClass,+ EverReceived: s.everReceived,+ }+ if !s.failingSince.IsZero() {+ h.FailingForSeconds = time.Since(s.failingSince).Seconds()+ }+ if !s.lastMessageAt.IsZero() {+ h.SinceLastMessage = time.Since(s.lastMessageAt)+ }+ return h+}++// notResolvingLocked reports whether the current run of failures has+// outlived any explanation a retry would fix. A permanent classification is+// immediately not-resolving; a transient one has to earn it by lasting.+//+// Deliberately not "no message in N seconds": a quiet topic is a legitimate+// state and judging it would make an idle deployment look broken, which is+// the mirror image of the defect this file exists for.+func (s *SourceState) notResolvingLocked() bool {+ if s.permanent {+ return true+ }+ if s.failingSince.IsZero() {+ return false+ }+ return time.Since(s.failingSince) >= s.stuckAfter+}++// MarkAttached records that the loop has begun iterating the subscription.+func (s *SourceState) MarkAttached() {+ if s == nil {+ return+ }+ s.mu.Lock()+ s.attached = true+ s.mu.Unlock()+ sourceAttached.WithLabelValues(s.topic).Set(1)+}++// MarkDetached records that the loop has stopped. reason is logged so a+// subscription that ends says so, which is the whole point.+func (s *SourceState) MarkDetached(reason string) {+ if s == nil {+ return+ }+ s.mu.Lock()+ wasAttached := s.attached+ s.attached = false+ s.mu.Unlock()+ sourceAttached.WithLabelValues(s.topic).Set(0)+ if wasAttached {+ log.Warn().Str("topic", s.topic).Str("reason", reason).+ Msg("graph_ws: consumer detached from its topic; no envelopes will reach subscribers")+ }+}++// RecordMessage resets the failure run after a message arrives, and says so+// if the source had been failing. A recovery that is not logged leaves the+// last line in the log describing a fault that has since cleared.+func (s *SourceState) RecordMessage() {+ if s == nil {+ return+ }+ s.mu.Lock()+ failures := s.consecutive+ since := s.failingSince+ s.consecutive = 0+ s.failingSince = time.Time{}+ s.lastError = ""+ s.lastAdvice = ""+ s.lastClass = ""+ s.lastMessageAt = time.Now()+ s.everReceived = true+ s.mu.Unlock()++ sourceStuck.WithLabelValues(s.topic).Set(0)+ if failures > 0 {+ event := log.Info()+ if !since.IsZero() {+ event = event.Dur("failing_for", time.Since(since))+ }+ event.Str("topic", s.topic).Uint64("consecutive_failures", failures).+ Msg("graph_ws: source recovered")+ }+}++// RecordPoison counts one unreadable envelope.+//+// It clears the failure run for the same reason RecordMessage does: a poison+// envelope only exists because ReadMessage returned, so the subscription is+// demonstrably working. Leaving the run set would let a stream of malformed+// envelopes from one bad producer be reported as a source that is not+// resolving, which is the opposite of what is happening.+func (s *SourceState) RecordPoison(err error) {+ if s == nil {+ return+ }+ s.mu.Lock()+ s.poisonMessages+++ count := s.poisonMessages+ s.consecutive = 0+ s.failingSince = time.Time{}+ s.lastMessageAt = time.Now()+ s.everReceived = true+ s.mu.Unlock()+ sourceErrors.WithLabelValues(s.topic, string(ClassPoison)).Inc()+ sourceStuck.WithLabelValues(s.topic).Set(0)+ log.Warn().Err(err).Str("topic", s.topic).Uint64("poison_messages", count).+ Msg("graph_ws: undecodable envelope skipped; the subscription is unaffected")+}++// RecordFailure classifies err, updates the counters, and logs it at a level+// that matches what an operator can do about it.+//+// Returns the class and how long to wait before the next attempt. A caller+// that gets ClassPermanent should stop: the wait is meaningless because no+// number of retries changes the answer.+func (s *SourceState) RecordFailure(err error) (FailureClass, time.Duration) {+ class, advice := classify(err)+ if class == ClassPoison {+ s.RecordPoison(err)+ return class, 0+ }+ if s == nil {+ logFailure(class, "unknown", advice, err, 1, 0, false)+ return class, backoffMin+ }++ now := time.Now()+ s.mu.Lock()+ s.consecutive+++ if s.failingSince.IsZero() {+ s.failingSince = now+ }+ s.lastError = truncate(err.Error(), 300)+ s.lastClass = class+ s.lastAdvice = advice+ if class == ClassPermanent {+ s.permanentFailures+++ s.permanent = true+ s.permanentAdvice = advice+ } else {+ s.transientFailures+++ }+ consecutive := s.consecutive+ failingFor := now.Sub(s.failingSince)+ notResolving := s.notResolvingLocked()+ // Rate limit on the *text* of the error, so a changed error is always+ // reported immediately and only genuine repetition is suppressed.+ signature := string(class) + "|" + s.lastError+ shouldLog := signature != s.lastLoggedSignature || now.Sub(s.lastLoggedAt) >= repeatEvery+ if shouldLog {+ s.lastLoggedAt = now+ s.lastLoggedSignature = signature+ }+ topic := s.topic+ s.mu.Unlock()++ sourceErrors.WithLabelValues(topic, string(class)).Inc()+ if notResolving {+ sourceStuck.WithLabelValues(topic).Set(1)+ }+ if shouldLog {+ logFailure(class, topic, advice, err, consecutive, failingFor, notResolving)+ }+ return class, backoffFor(consecutive)+}++// ObserveReaderError records an error the Kafka reader reported to its own+// error logger rather than returning from ReadMessage. Those are the dial,+// join, and rebalance failures a consumer group retries internally — the+// ones that were being discarded entirely.+func (s *SourceState) ObserveReaderError(message string) {+ s.RecordFailure(readerError(message))+}++// readerError turns kafka-go's formatted log line back into something+// classify can reason about.+//+// The library hands over a string, never an error value, so the+// classification has to come from the text. Every pattern is matched against+// the `Title()` spelling kafka-go prints for a protocol code, and the+// permanent ones are the same set `permanentProtocolErrors` names — stated+// twice because the two arrive by different routes, and kept honest by+// TestEveryPermanentCodeIsAlsoRecognisedInAReaderLogLine.+//+// A pattern that carries advice without being permanent is deliberate: an+// absent topic is worth explaining and is not worth stopping for.+func readerError(message string) error {+ lower := strings.ToLower(message)+ for _, p := range readerPatterns {+ if !strings.Contains(lower, p.substring) {+ continue+ }+ if p.permanent {+ return Permanent(errors.New(message), p.advice)+ }+ return &advisedError{err: errors.New(message), advice: p.advice}+ }+ return errors.New(message)+}++// advisedError is a transient error that still has a known remedy.+type advisedError struct {+ err error+ advice string+}++func (e *advisedError) Error() string { return e.err.Error() }+func (e *advisedError) Unwrap() error { return e.err }++var readerPatterns = []struct {+ substring string+ permanent bool+ advice string+}{+ {"topic authorization failed", true, "grant this client read on the topic, or point it at one it may read"},+ {"group authorization failed", true, "grant this client access to the consumer group, or change AISOC_GRAPH_WS_GROUP_ID"},+ {"cluster authorization failed", true, "the broker refused this principal; check the credentials this service runs with"},+ {"sasl authentication failed", true, "the broker rejected these credentials; they will not start working on their own"},+ {"unsupported sasl mechanism", true, "the broker does not offer this SASL mechanism; reconfigure the client"},+ {"illegal sasl state", true, "the SASL handshake was attempted out of order; this is a client configuration fault"},+ {"unsupported version", true, "this client and this broker cannot agree on a protocol version"},+ {"invalid topic", true, "the topic name is not valid; check AISOC_GRAPH_UPDATES_TOPIC"},+ {"invalid group id", true, "the consumer group id is not valid; check AISOC_GRAPH_WS_GROUP_ID"},+ {"security disabled", true, "the broker has security disabled and cannot answer this request"},+ {"unknown topic or partition", false, "create the topic, or enable auto-creation on the broker"},+ {"connection refused", false, "nothing is listening on the broker address; check KAFKA_BROKERS and that the broker is up"},+ {"no such host", false, "the broker hostname does not resolve; check KAFKA_BROKERS"},+ {"i/o timeout", false, "the broker accepted no answer in time; check network reachability between this service and the broker"},+}++func logFailure(class FailureClass, topic, advice string, err error, consecutive uint64, failingFor time.Duration, notResolving bool) {+ event := log.Warn()+ if class == ClassPermanent || notResolving {+ event = log.Error()+ }+ event = event.Err(err).+ Str("topic", topic).+ Str("class", string(class)).+ Uint64("consecutive_failures", consecutive)+ if failingFor > 0 {+ event = event.Dur("failing_for", failingFor)+ }+ if advice != "" {+ event = event.Str("operator_action", advice)+ }+ switch {+ case class == ClassPermanent:+ event.Msg("graph_ws: source failure will not clear on its own; retrying is not progress")+ case notResolving:+ event.Msg("graph_ws: source has been failing for longer than a transient fault explains; treat this as a misconfiguration, not churn")+ default:+ event.Msg("graph_ws: source failure; retrying")+ }+}++// backoffFor grows the wait with the length of the failure run, capped. The+// first few retries stay fast so a broker blip costs nothing; a sustained+// outage stops being a reconnect storm.+func backoffFor(consecutive uint64) time.Duration {+ wait := backoffMin+ for i := uint64(1); i < consecutive && wait < backoffMax; i++ {+ wait *= 2+ }+ if wait > backoffMax {+ wait = backoffMax+ }+ return wait+}++func truncate(s string, n int) string {+ if len(s) <= n {+ return s+ }+ return s[:n] + "…"+}++// sleepFor waits for d or until the loop is asked to stop, whichever first.+// Returns false if the loop should exit.+func sleepFor(ctx context.Context, stopCh <-chan struct{}, d time.Duration) bool {+ if d <= 0 {+ return true+ }+ timer := time.NewTimer(d)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return false+ case <-stopCh:+ return false+ case <-timer.C:+ return true+ }+}++// isContextError keeps an ordinary shutdown out of the failure counters. A+// cancelled context is the operator stopping the service, not a fault.+func isContextError(err error) bool {+ return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)+}diff --git a/services/ingest/internal/graph_ws/source_health_test.go b/services/ingest/internal/graph_ws/source_health_test.gonew file mode 100644index 000000000..b9c8b2222--- /dev/null+++ b/services/ingest/internal/graph_ws/source_health_test.go@@ -0,0 +1,555 @@+// Tests for failure classification and reporting in the graph_ws consumer.+//+// The property under test is the one the consume loop could not express+// before: a condition that will never resolve is reported differently from+// one that might, and neither is silent.+package graph_ws++import (+ "context"+ "encoding/json"+ "errors"+ "net"+ "net/http"+ "net/http/httptest"+ "sort"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/beenuar/aisoc/services/ingest/internal/graph"+ kafka "github.com/segmentio/kafka-go"+)++// scriptedSource returns each error in turn and then blocks, so a test can+// drive an exact failure sequence without timing assumptions.+type scriptedSource struct {+ mu sync.Mutex+ steps []step+ index int+ calls int+ blocked chan struct{}+}++type step struct {+ env graph.GraphUpdate+ err error+}++func newScriptedSource(steps ...step) *scriptedSource {+ return &scriptedSource{steps: steps, blocked: make(chan struct{})}+}++func (s *scriptedSource) Next(ctx context.Context) (graph.GraphUpdate, error) {+ s.mu.Lock()+ s.calls+++ if s.index < len(s.steps) {+ next := s.steps[s.index]+ s.index+++ s.mu.Unlock()+ return next.env, next.err+ }+ s.mu.Unlock()+ // Out of script: block like a real consumer waiting on a quiet topic.+ select {+ case <-ctx.Done():+ return graph.GraphUpdate{}, ctx.Err()+ case <-s.blocked:+ return graph.GraphUpdate{}, errors.New("closed")+ }+}++func (s *scriptedSource) Close() error { return nil }++// repeatingSource returns the same error on every call, forever.+type repeatingSource struct{ err error }++func (r *repeatingSource) Next(context.Context) (graph.GraphUpdate, error) {+ return graph.GraphUpdate{}, r.err+}+func (r *repeatingSource) Close() error { return nil }++func waitFor(t *testing.T, what string, cond func() bool) {+ t.Helper()+ deadline := time.Now().Add(3 * time.Second)+ for time.Now().Before(deadline) {+ if cond() {+ return+ }+ time.Sleep(5 * time.Millisecond)+ }+ t.Fatalf("timed out waiting for %s", what)+}++// TestClassifyNamesWhatCanBeDone enumerates what the classifier *credits* as+// transient, not only what it flags. A classifier that answered "transient"+// to everything would satisfy any test that only checked the permanent+// cases, and "transient" is the answer that makes a failure look like churn.+func TestClassifyNamesWhatCanBeDone(t *testing.T) {+ cases := []struct {+ name string+ err error+ want FailureClass+ regex string+ }{+ {"a dial failure may clear", errors.New("dial tcp 10.0.0.1:9092: connect: connection refused"), ClassTransient, ""},+ {"a leader election may clear", kafka.LeaderNotAvailable, ClassTransient, ""},+ {"a rebalance in progress may clear", kafka.RebalanceInProgress, ClassTransient, ""},+ {"an absent topic may clear, and says who can clear it", kafka.UnknownTopicOrPartition, ClassTransient, "create the topic"},+ {"an authorization failure may not", kafka.TopicAuthorizationFailed, ClassPermanent, "grant this client read"},+ {"an unsupported SASL mechanism may not", kafka.UnsupportedSASLMechanism, ClassPermanent, "reconfigure the client"},+ {"an explicitly permanent error carries its advice", Permanent(errors.New("no brokers"), "set KAFKA_BROKERS"), ClassPermanent, "set KAFKA_BROKERS"},+ {"an undecodable envelope is about the message", Poison(errors.New("invalid character")), ClassPoison, "subscription is unaffected"},+ {"a raw json error is also about the message", &json.SyntaxError{}, ClassPoison, "subscription is unaffected"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, advice := classify(tc.err)+ if got != tc.want {+ t.Fatalf("classify(%v) = %q, want %q", tc.err, got, tc.want)+ }+ if tc.regex != "" && !strings.Contains(advice, tc.regex) {+ t.Fatalf("advice %q does not mention %q", advice, tc.regex)+ }+ })+ }+}++// TestReaderErrorClassification covers the strings kafka-go hands to its+// error logger, which is the only form those failures ever take.+func TestReaderErrorClassification(t *testing.T) {+ cases := []struct {+ name string+ line string+ want FailureClass+ }{+ {+ "an unreachable broker is retriable until it is not",+ "error initializing the kafka reader for partition 0 of graph: dial tcp 10.1.2.3:9092: i/o timeout",+ ClassTransient,+ },+ {+ "a refused ACL is not",+ "Error reading partition assignments for topic graph: [29] Topic Authorization Failed",+ ClassPermanent,+ },+ {+ // Retriable: it appears the moment somebody creates it. What+ // the operator gets is the advice, not a stopped consumer.+ "an absent topic keeps being retried but says who can fix it",+ "the kafka reader got an unknown error reading partition 0: [3] Unknown Topic Or Partition",+ ClassTransient,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, advice := classify(readerError(tc.line))+ if got != tc.want {+ t.Fatalf("classify(readerError(%q)) = %q, want %q", tc.line, got, tc.want)+ }+ if advice == "" {+ t.Fatalf("no operator action for %q", tc.line)+ }+ })+ }+}++// TestTransientFailureIsCountedAndRetried is the old behaviour made visible:+// the loop still survives, but the error is now recorded rather than dropped.+func TestTransientFailureIsCountedAndRetried(t *testing.T) {+ src := newScriptedSource(+ step{err: errors.New("dial tcp: connection refused")},+ step{env: graph.GraphUpdate{EntityID: "e1", TenantID: "t", SchemaVersion: graph.SchemaVersion}},+ )+ b := New(src, Options{Topic: "test-transient"})+ sub := b.Subscribe("t")+ defer b.Unsubscribe(sub)++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ b.Start(ctx)+ defer b.Stop()++ select {+ case env := <-sub.Updates:+ if env.EntityID != "e1" {+ t.Fatalf("unexpected envelope %q", env.EntityID)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("loop did not recover from a transient failure")+ }++ health := b.Health()+ if health.TransientFailures != 1 {+ t.Fatalf("transient failures = %d, want 1", health.TransientFailures)+ }+ if !health.Attached {+ t.Fatal("a transient failure must not detach the subscription")+ }+ // Recovery clears the run, so the next report does not describe a fault+ // that has already cleared.+ if health.ConsecutiveFailures != 0 || health.NotResolving {+ t.Fatalf("after a delivered envelope: consecutive=%d not_resolving=%t, want 0/false",+ health.ConsecutiveFailures, health.NotResolving)+ }+}++// TestPermanentFailureStopsTheLoopAndSaysSo is the defect this change exists+// for, inverted: a fault no retry can clear must not be retried in silence.+func TestPermanentFailureStopsTheLoopAndSaysSo(t *testing.T) {+ src := &repeatingSource{err: Permanent(kafka.TopicAuthorizationFailed, "grant read on the topic")}+ b := New(src, Options{Topic: "test-permanent"})++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ b.Start(ctx)+ defer b.Stop()++ waitFor(t, "the loop to stop on a permanent failure", func() bool {+ h := b.Health()+ return h.PermanentFailure && !h.Attached+ })++ health := b.Health()+ if !health.PermanentFailure {+ t.Fatal("a permanent failure must be reported as permanent")+ }+ if health.Healthy() {+ t.Fatal("Healthy() must be false while the source is permanently failed")+ }+ if !strings.Contains(health.Reason(), "grant read on the topic") {+ t.Fatalf("reason %q does not carry the operator action", health.Reason())+ }+ if health.PermanentFailures != 1 {+ t.Fatalf("permanent failures = %d, want exactly 1 — a permanent fault must not be retried",+ health.PermanentFailures)+ }+}++// TestTransientFailureEscalatesWhenItOutlivesItsExcuse covers the state that+// is a duration rather than a class: a `no such host` can be a startup race+// for a few seconds and a variable nobody set for ever. The loop reports the+// first and then stops calling it that.+func TestTransientFailureEscalatesWhenItOutlivesItsExcuse(t *testing.T) {+ src := &repeatingSource{err: errors.New("dial tcp: lookup kafka: no such host")}+ b := New(src, Options{Topic: "test-stuck", StuckAfter: 50 * time.Millisecond})++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ b.Start(ctx)+ defer b.Stop()++ if h := b.Health(); h.NotResolving {+ t.Fatal("a failure must not be called not-resolving before it has lasted")+ }+ waitFor(t, "the failure to be reported as not resolving", func() bool {+ return b.Health().NotResolving+ })+ health := b.Health()+ if !health.Attached {+ t.Fatal("the loop should still be retrying — the condition may yet clear")+ }+ if health.PermanentFailure {+ t.Fatal("not-resolving is an observation about duration, not a protocol verdict")+ }+ if health.Healthy() {+ t.Fatal("a source failing past its transient explanation is not healthy")+ }+ if !strings.Contains(health.Reason(), "no such host") {+ t.Fatalf("reason %q does not name the failure", health.Reason())+ }+}++// TestBackoffGrowsAndIsCapped: a flat 50ms against an unreachable broker is+// twenty reconnects a second forever.+func TestBackoffGrowsAndIsCapped(t *testing.T) {+ if got := backoffFor(1); got != backoffMin {+ t.Fatalf("first retry waited %s, want %s", got, backoffMin)+ }+ if got := backoffFor(3); got != 4*backoffMin {+ t.Fatalf("third retry waited %s, want %s", got, 4*backoffMin)+ }+ if got := backoffFor(1000); got != backoffMax {+ t.Fatalf("a long outage waited %s, want the %s cap", got, backoffMax)+ }+}++// TestPoisonEnvelopeDoesNotDetachTheSubscription: one unreadable message is+// not a broken topic, and must not be reported as one.+func TestPoisonEnvelopeDoesNotDetachTheSubscription(t *testing.T) {+ src := newScriptedSource(+ step{err: Poison(errors.New("invalid character 'x'"))},+ step{env: graph.GraphUpdate{EntityID: "after-poison", TenantID: "t", SchemaVersion: graph.SchemaVersion}},+ )+ b := New(src, Options{Topic: "test-poison", StuckAfter: 20 * time.Millisecond})+ sub := b.Subscribe("t")+ defer b.Unsubscribe(sub)++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ b.Start(ctx)+ defer b.Stop()++ select {+ case env := <-sub.Updates:+ if env.EntityID != "after-poison" {+ t.Fatalf("unexpected envelope %q", env.EntityID)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("a poison envelope stopped the subscription")+ }++ health := b.Health()+ if health.PoisonMessages != 1 {+ t.Fatalf("poison messages = %d, want 1", health.PoisonMessages)+ }+ if health.TransientFailures != 0 || health.PermanentFailures != 0 {+ t.Fatalf("a poison envelope was counted as a source failure: %+v", health)+ }+ if !health.Healthy() {+ t.Fatalf("the subscription is working; health says %q", health.Reason())+ }+}++// TestCleanShutdownIsNotAFailure: a cancelled context is an operator, not a+// fault, and must not leave a failure as the last thing recorded.+func TestCleanShutdownIsNotAFailure(t *testing.T) {+ src := &repeatingSource{err: context.Canceled}+ b := New(src, Options{Topic: "test-shutdown"})+ ctx, cancel := context.WithCancel(context.Background())+ b.Start(ctx)+ cancel()+ b.Stop()++ health := b.Health()+ if health.TransientFailures != 0 || health.PermanentFailures != 0 {+ t.Fatalf("shutdown was counted as a failure: %+v", health)+ }+ if health.Attached {+ t.Fatal("a stopped loop must report detached")+ }+}++// TestStreamRouteRefusesWhenTheSourceIsDetached. Completing the handshake+// would hand the client a socket that stays silent, which is exactly the+// state nobody could tell apart from a quiet estate.+func TestStreamRouteRefusesWhenTheSourceIsDetached(t *testing.T) {+ src := &repeatingSource{err: Permanent(errors.New("topic missing"), "create the topic")}+ b := New(src, Options{Topic: "test-route"})+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ b.Start(ctx)+ defer b.Stop()+ waitFor(t, "the source to report a permanent failure", func() bool { return b.Health().PermanentFailure })++ req := httptest.NewRequest(http.MethodGet, "/v1/graph_ws/stream?tenant_id=t1", nil)+ req.Header.Set("Connection", "Upgrade")+ req.Header.Set("Upgrade", "websocket")+ req.Header.Set("Sec-WebSocket-Version", "13")+ req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")+ rec := httptest.NewRecorder()++ NewServer(b).Handler().ServeHTTP(rec, req)++ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("status = %d, want 503", rec.Code)+ }+ if !strings.Contains(rec.Body.String(), "create the topic") {+ t.Fatalf("body %q does not say what to do about it", rec.Body.String())+ }+}++// TestAnUnreachableBrokerSaysSo drives a real kafka.Reader at a port nothing+// is listening on.+//+// This is the case the whole change is about, and it is the one a fake+// source cannot prove: with a GroupID set, kafka-go's dial failures never+// return from ReadMessage — they go to the reader's ErrorLogger, which+// defaults to a silent logger. Before this change the loop sat blocked and+// every one of those errors was discarded inside the library.+func TestAnUnreachableBrokerSaysSo(t *testing.T) {+ // A port that is closed rather than a hostname that does not resolve:+ // connection-refused is immediate and needs no DNS, so the test neither+ // touches the network nor waits on a resolver timeout.+ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("cannot reserve a port: %v", err)+ }+ addr := listener.Addr().String()+ if err := listener.Close(); err != nil {+ t.Fatalf("cannot close the reserved port: %v", err)+ }++ health := NewSourceState("test-unreachable-broker", 500*time.Millisecond)+ src, err := NewKafkaSource(KafkaSourceConfig{+ Brokers: addr,+ Topic: "security.graph_updates",+ GroupID: "graph-ws-unreachable-test",+ Health: health,+ })+ if err != nil {+ t.Fatalf("NewKafkaSource: %v", err)+ }+ defer func() { _ = src.Close() }()++ b := New(src, Options{Health: health})+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ b.Start(ctx)+ defer b.Stop()++ deadline := time.Now().Add(15 * time.Second)+ for time.Now().Before(deadline) {+ if h := b.Health(); h.ConsecutiveFailures > 0 {+ break+ }+ time.Sleep(25 * time.Millisecond)+ }++ h := b.Health()+ if h.ConsecutiveFailures == 0 {+ t.Fatal("an unreachable broker produced no recorded failure — the reader's errors are still being discarded")+ }+ if h.LastError == "" {+ t.Fatal("a failure was counted with no error text; an operator learns nothing from a counter alone")+ }+ if !strings.Contains(h.LastError, addr) && !strings.Contains(h.LastError, "connection refused") {+ t.Fatalf("last error %q names neither the broker nor the failure", h.LastError)+ }+ if h.Advice == "" {+ t.Fatal("no operator action was offered for an unreachable broker")+ }+ t.Logf("unreachable broker at %s reported after %d failure(s): %s (%s)",+ addr, h.ConsecutiveFailures, h.LastError, h.Advice)++ // It is reported as transient at first, because a broker coming back is+ // exactly what a retry is for. What must not happen is that it stays+ // described that way forever.+ waitFor(t, "the outage to stop being described as churn", func() bool {+ return b.Health().NotResolving+ })+ stuck := b.Health()+ if stuck.Healthy() {+ t.Fatalf("a source that cannot reach its broker reported healthy: %+v", stuck)+ }+ if !strings.Contains(stuck.Reason(), "failing for") {+ t.Fatalf("reason %q does not say how long it has been failing", stuck.Reason())+ }+ t.Logf("reason: %s", stuck.Reason())+}++// TestNewKafkaSourceRefusesAnEmptyBrokerList: a misconfiguration caught at+// construction is one that never becomes a silent retry.+func TestNewKafkaSourceRefusesAnEmptyBrokerList(t *testing.T) {+ for _, brokers := range []string{"", " ", ",", " , "} {+ if _, err := NewKafkaSource(KafkaSourceConfig{Brokers: brokers, Topic: "t"}); err == nil {+ t.Fatalf("NewKafkaSource accepted brokers=%q", brokers)+ }+ }+}++// TestHealthIsSafeWithoutAState: a nil SourceState must not panic, because+// the fallback path is the one taken when something is already wrong.+func TestHealthIsSafeWithoutAState(t *testing.T) {+ var nilState *SourceState+ nilState.MarkAttached()+ nilState.MarkDetached("test")+ nilState.RecordMessage()+ nilState.RecordPoison(errors.New("x"))+ nilState.ObserveReaderError("dial tcp: connection refused")+ if class, _ := nilState.RecordFailure(errors.New("boom")); class != ClassTransient {+ t.Fatalf("nil state classified as %q", class)+ }+ if h := nilState.Health(); h.Attached {+ t.Fatalf("a nil state reported attached: %+v", h)+ }+}++// TestClassifyCreditsOnlyTheCodesItMeansTo walks the entire Kafka protocol+// error table and prints what the classifier *credits*, rather than only+// asserting the handful of codes it flags.+//+// That direction is the one that finds the blind spot. A test listing three+// permanent codes passes just as well against a classifier that calls+// everything permanent, and a classifier that did would stop this consumer+// on every rebalance. Deriving the set from `kafka.Error.Temporary()` would+// have done exactly that: the protocol's "retriable" column says no for+// REBALANCE_IN_PROGRESS, which happens on every deploy.+func TestClassifyCreditsOnlyTheCodesItMeansTo(t *testing.T) {+ // Codes a consumer group resolves by rejoining, which upstream also+ // reports as non-retriable. Stopping the loop on any of these would be+ // an outage introduced by the fix.+ mustBeTransient := []kafka.Error{+ kafka.RebalanceInProgress,+ kafka.UnknownMemberId,+ kafka.IllegalGeneration,+ kafka.MemberIDRequired,+ kafka.UnknownTopicOrPartition,+ kafka.NotCoordinatorForGroup,+ kafka.GroupLoadInProgress,+ kafka.GroupCoordinatorNotAvailable,+ kafka.LeaderNotAvailable,+ kafka.RequestTimedOut,+ kafka.NetworkException,+ }+ for _, code := range mustBeTransient {+ if class, _ := classify(code); class != ClassTransient {+ t.Errorf("%v (code %d) classified %q; a retry or a rejoin clears it and stopping the loop would be an outage",+ code, int(code), class)+ }+ }++ // The whole table, both directions: nothing outside the declared set may+ // be permanent, and everything inside it must be.+ var credited, flagged []string+ for code := kafka.Error(1); code <= kafka.Error(110); code++ {+ if code.Title() == "" || (code.Title() == "Unknown" && code != kafka.Unknown) {+ continue // a gap in the table, not a code this client knows+ }+ class, advice := classify(code)+ _, declared := permanentProtocolErrors[code]+ switch {+ case class == ClassPermanent && !declared:+ t.Errorf("%v (code %d) classified permanent but is not in permanentProtocolErrors", code, int(code))+ case class != ClassPermanent && declared:+ t.Errorf("%v (code %d) is declared permanent but classified %q", code, int(code), class)+ }+ if class == ClassPermanent {+ if advice == "" {+ t.Errorf("%v is permanent with no operator action; a permanent verdict with no next move is just a louder silence", code)+ }+ flagged = append(flagged, code.Title())+ } else {+ credited = append(credited, code.Title())+ }+ }+ sort.Strings(flagged)+ t.Logf("permanent (%d): %s", len(flagged), strings.Join(flagged, ", "))+ t.Logf("retried (%d): %s", len(credited), strings.Join(credited, ", "))+ if len(credited) < 50 {+ t.Fatalf("only %d codes were walked; the enumeration is not covering the table", len(credited))+ }+ if len(flagged) != len(permanentProtocolErrors) {+ t.Fatalf("walked %d permanent codes, declared %d", len(flagged), len(permanentProtocolErrors))+ }+}++// TestEveryPermanentCodeIsAlsoRecognisedInAReaderLogLine closes the gap+// between the two routes a protocol error takes to this package. One arrives+// as a kafka.Error from ReadMessage; the other arrives as text in the+// reader's error logger, which is where the consumer group's failures go.+// A code recognised on one route and not the other is a permanent failure+// reported as churn on whichever route it happens to take.+func TestEveryPermanentCodeIsAlsoRecognisedInAReaderLogLine(t *testing.T) {+ for code := range permanentProtocolErrors {+ line := "kafka reader: [" + code.Title() + "] while fetching"+ class, advice := classify(readerError(line))+ if class != ClassPermanent {+ t.Errorf("%q from the reader log classified %q, but the same code from ReadMessage is permanent", line, class)+ }+ if advice == "" {+ t.Errorf("%q carries no operator action", line)+ }+ }+}diff --git a/services/ingest/internal/handler/handler.go b/services/ingest/internal/handler/handler.goindex 8a1394881..de9b99c94 100644--- a/services/ingest/internal/handler/handler.go+++ b/services/ingest/internal/handler/handler.go@@ -6,6 +6,7 @@ import ("encoding/json""fmt""net/http"+ "sort""time""github.com/beenuar/aisoc/services/ingest/internal/config"@@ -31,18 +32,47 @@ type SnapshotApplier interface {Apply(ctx context.Context, ev *graph.Event)}+// SubscriptionStatus is what a background subscription reports about itself+// to /readyz. Declared here, with no dependency on the package that owns the+// subscription, so wiring one up cannot create an import cycle.+type SubscriptionStatus struct {+ // Attached: the loop is iterating its source right now.+ Attached bool `json:"attached"`+ // NotResolving: it has been failing for longer than a transient fault+ // explains, or the failure is one no retry can clear. This is the field+ // that separates "quiet" from "broken", which is the distinction a+ // probe reporting only on the process cannot make.+ NotResolving bool `json:"not_resolving"`+ // Detail is the operator-facing reason, empty when healthy.+ Detail string `json:"detail,omitempty"`+}+// Handler holds handler dependenciestype Handler struct {- norm *normalizer.Normalizer- pub *publisher.Publisher- graph GraphWriter- snapshot SnapshotApplier- cfg *config.Config+ norm *normalizer.Normalizer+ pub *publisher.Publisher+ graph GraphWriter+ snapshot SnapshotApplier+ cfg *config.Config+ subscriptions map[string]func() SubscriptionStatus}// New creates a new Handlerfunc New(norm *normalizer.Normalizer, pub *publisher.Publisher, cfg *config.Config) *Handler {- return &Handler{norm: norm, pub: pub, cfg: cfg}+ return &Handler{norm: norm, pub: pub, cfg: cfg, subscriptions: map[string]func() SubscriptionStatus{}}+}++// RegisterSubscription makes /readyz report on a background consumer.+//+// Call once per subscription the service owns, before serving. probe must be+// cheap and non-blocking — it runs on every readiness request — so it should+// read state the consumer already maintains rather than round-trip to a+// broker.+func (h *Handler) RegisterSubscription(name string, probe func() SubscriptionStatus) {+ if h.subscriptions == nil {+ h.subscriptions = map[string]func() SubscriptionStatus{}+ }+ h.subscriptions[name] = probe}// SetGraphWriter wires in the graph projection writer. nil disables graph@@ -198,33 +228,95 @@ func (h *Handler) Livez(w http.ResponseWriter, r *http.Request) {//// 503 with the reason, rather than 200 with a status field, so a load// balancer and a human both get a usable answer.+//+// Subscriptions are reported, not voted on+// ----------------------------------------+// Every registered background subscription is listed in the body whether or+// not anything is wrong, so a 200 says which ones were checked rather than+// only that nothing failed — a detached consumer behind a 200 with no+// mention of it is precisely what made the UEBA defect invisible.+//+// What a detached subscription does NOT do is flip the status code. Unlike+// the Python services, where consuming a topic IS the service's job, ingest+// serves two different kinds of traffic on one port: the publish path+// (/v1/ingest, /v1/inbox) and the opt-in graph-update WebSocket. Failing+// readiness for the second would pull the pipeline's front door out of the+// load balancer over an auxiliary feature, dropping events to fix a+// broadcast. The surface that depends on the subscription reports on it+// 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()+ subs := h.subscriptionReport()+ body := map[string]interface{}{+ "service": "ingest",+ // Present on every response, including the failing ones. A field+ // that only renders on the happy path is absent at exactly the+ // moment somebody is reading the output to find out what is wrong.+ "subscriptions": subs,+ "timestamp": time.Now().UTC().Format(time.RFC3339),+ }+ // 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 h.pub == nil {- writeJSON(w, http.StatusServiceUnavailable, map[string]interface{}{- "status": "not_ready",- "service": "ingest",- "reason": "no kafka publisher configured",- })+ body["status"] = "not_ready"+ body["reason"] = "no kafka publisher configured"+ writeJSON(w, http.StatusServiceUnavailable, body)return}if err := h.pub.Ready(ctx); err != nil {- writeJSON(w, http.StatusServiceUnavailable, map[string]interface{}{- "status": "not_ready",- "service": "ingest",- "reason": err.Error(),- "hint": "docker compose logs kafka | tail -40",- })+ body["status"] = "not_ready"+ body["reason"] = err.Error()+ body["hint"] = "docker compose logs kafka | tail -40"+ writeJSON(w, http.StatusServiceUnavailable, body)return}- writeJSON(w, http.StatusOK, map[string]interface{}{- "status": "ready",- "service": "ingest",- "checks": map[string]string{"kafka": "reachable"},- "timestamp": time.Now().UTC().Format(time.RFC3339),- })+ body["status"] = "ready"+ body["checks"] = map[string]string{"kafka": "reachable"}+ if _, degraded := body["degraded_subscriptions"]; degraded {+ body["status"] = "ready_degraded"+ }+ writeJSON(w, http.StatusOK, body)+}++// subscriptionReport evaluates every registered probe. A probe that panics+// is reported as detached rather than taking the readiness endpoint down+// with it: asking a live object whether it is working must not be able to+// make the answer unavailable.+func (h *Handler) subscriptionReport() map[string]SubscriptionStatus {+ out := make(map[string]SubscriptionStatus, len(h.subscriptions))+ for name, probe := range h.subscriptions {+ out[name] = safeProbe(name, probe)+ }+ return out+}++func safeProbe(name string, probe func() SubscriptionStatus) (status SubscriptionStatus) {+ defer func() {+ if rec := recover(); rec != nil {+ log.Error().Str("subscription", name).Interface("panic", rec).+ Msg("readiness probe panicked; reporting the subscription as detached")+ status = SubscriptionStatus{Attached: false, NotResolving: true, Detail: "probe panicked"}+ }+ }()+ return probe()+}++func degradedSubscriptions(subs map[string]SubscriptionStatus) []string {+ var names []string+ for name, status := range subs {+ if !status.Attached || status.NotResolving {+ names = append(names, name)+ }+ }+ sort.Strings(names)+ return names}func writeJSON(w http.ResponseWriter, status int, v interface{}) {diff --git a/services/ingest/internal/handler/readyz_test.go b/services/ingest/internal/handler/readyz_test.gonew file mode 100644index 000000000..b333987c3--- /dev/null+++ b/services/ingest/internal/handler/readyz_test.go@@ -0,0 +1,133 @@+// readyz_test.go — what the readiness probe says about background+// subscriptions.+//+// The property under test is the one the UEBA defect turned on: a consumer+// detached from its topic behind a 200 that never mentions it is+// indistinguishable from an idle one. Readiness has to name every+// subscription it knows about, in the healthy case too, or a clean answer+// only means "nothing I looked at was wrong" without saying what that was.+package handler++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/beenuar/aisoc/services/ingest/internal/config"+)++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,+ // and the subscription report has to survive it — a probe that only+ // renders on the happy path reports nothing at the moment it matters.+ return New(nil, nil, &config.Config{})+}++func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {+ t.Helper()+ var body map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatalf("readiness body is not JSON: %v (%s)", err, rec.Body.String())+ }+ return body+}++func callReadyz(t *testing.T, h *Handler) (*httptest.ResponseRecorder, map[string]any) {+ t.Helper()+ rec := httptest.NewRecorder()+ h.Readyz(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))+ return rec, decodeBody(t, rec)+}++func TestReadyzNamesAnAttachedSubscription(t *testing.T) {+ h := newReadyHandler()+ h.RegisterSubscription("graph_ws", func() SubscriptionStatus {+ return SubscriptionStatus{Attached: true}+ })++ _, body := callReadyz(t, h)+ subs, ok := body["subscriptions"].(map[string]any)+ if !ok {+ t.Fatalf("no subscriptions block in %v", body)+ }+ entry, ok := subs["graph_ws"].(map[string]any)+ if !ok {+ t.Fatalf("graph_ws not named in %v", subs)+ }+ if entry["attached"] != true {+ t.Fatalf("attached subscription reported as %v", entry)+ }+ if _, degraded := body["degraded_subscriptions"]; degraded {+ t.Fatalf("a healthy subscription was reported as degraded: %v", body)+ }+}++func TestReadyzReportsADetachedSubscription(t *testing.T) {+ h := newReadyHandler()+ h.RegisterSubscription("graph_ws", func() SubscriptionStatus {+ return SubscriptionStatus{Attached: false, NotResolving: true, Detail: "permanent source failure on security.graph_updates"}+ })++ _, body := callReadyz(t, h)+ subs := body["subscriptions"].(map[string]any)+ entry := subs["graph_ws"].(map[string]any)+ if entry["attached"] != false || entry["not_resolving"] != true {+ t.Fatalf("detached subscription reported as %v", entry)+ }+ if entry["detail"] != "permanent source failure on security.graph_updates" {+ t.Fatalf("the reason did not survive into the body: %v", entry)+ }+ degraded, ok := body["degraded_subscriptions"].([]any)+ if !ok || len(degraded) != 1 || degraded[0] != "graph_ws" {+ t.Fatalf("degraded subscriptions = %v, want [graph_ws]", body["degraded_subscriptions"])+ }+}++// A subscription that is attached but has been failing longer than a+// transient fault explains is the case a boolean cannot express. Attached+// alone would report it healthy, which is the distinction this whole change+// is about.+func TestReadyzReportsAnAttachedButNotResolvingSubscription(t *testing.T) {+ h := newReadyHandler()+ h.RegisterSubscription("graph_ws", func() SubscriptionStatus {+ return SubscriptionStatus{Attached: true, NotResolving: true, Detail: "failing for 300s"}+ })++ _, body := callReadyz(t, h)+ degraded, ok := body["degraded_subscriptions"].([]any)+ if !ok || len(degraded) != 1 {+ t.Fatalf("an attached-but-stuck subscription was not reported as degraded: %v", body)+ }+}++func TestReadyzSurvivesAProbeThatPanics(t *testing.T) {+ h := newReadyHandler()+ h.RegisterSubscription("exploding", func() SubscriptionStatus {+ panic("probe blew up")+ })++ rec, body := callReadyz(t, h)+ if rec.Code == 0 {+ t.Fatal("no response was written")+ }+ subs := body["subscriptions"].(map[string]any)+ entry := subs["exploding"].(map[string]any)+ if entry["attached"] != false || entry["not_resolving"] != true {+ t.Fatalf("a panicking probe was credited as healthy: %v", entry)+ }+}++// With no subscription registered the block is present and empty, so a+// reader can tell "nothing is registered" from "the field was dropped".+func TestReadyzAlwaysCarriesTheSubscriptionBlock(t *testing.T) {+ _, body := callReadyz(t, newReadyHandler())+ subs, ok := body["subscriptions"].(map[string]any)+ if !ok {+ t.Fatalf("subscriptions block missing entirely from %v", body)+ }+ if len(subs) != 0 {+ t.Fatalf("expected an empty block, got %v", subs)+ }+}diff --git a/services/ingest/main.go b/services/ingest/main.goindex e6e24618a..742461408 100644--- a/services/ingest/main.go+++ b/services/ingest/main.go@@ -214,16 +214,36 @@ func main() {var graphWSServer *graph_ws.Servervar graphWSBroker *graph_ws.Broadcasterif cfg.GraphWSEnabled {+ // One state object shared by the source and the broadcaster: the+ // errors kafka-go reports to its own logger and the ones the consume+ // loop sees are the same subscription failing, and splitting them+ // across two records is how half of them stay invisible.+ graphWSHealth := graph_ws.NewSourceState(cfg.GraphUpdatesTopic, 0)src, err := graph_ws.NewKafkaSource(graph_ws.KafkaSourceConfig{Brokers: cfg.KafkaBrokers,Topic: cfg.GraphUpdatesTopic,GroupID: cfg.GraphWSGroupID,+ Health: graphWSHealth,})if err != nil {log.Warn().Err(err).Msg("graph_ws: disabled (Kafka source init failed)")} else {- graphWSBroker = graph_ws.New(src, graph_ws.Options{BufferSize: cfg.GraphWSSubscriberBuffer})+ graphWSBroker = graph_ws.New(src, graph_ws.Options{+ BufferSize: cfg.GraphWSSubscriberBuffer,+ Health: graphWSHealth,+ })graphWSServer = graph_ws.NewServer(graphWSBroker)+ // /readyz names this subscription and its state. A consumer+ // detached from its topic behind a 200 that never mentions it is+ // indistinguishable from an idle one.+ h.RegisterSubscription("graph_ws", func() handler.SubscriptionStatus {+ health := graphWSBroker.Health()+ return handler.SubscriptionStatus{+ Attached: health.Attached,+ NotResolving: health.NotResolving,+ Detail: health.Reason(),+ }+ })log.Info().Str("topic", cfg.GraphUpdatesTopic).Int("buffer", cfg.GraphWSSubscriberBuffer).diff --git a/services/osquery-tls/app/security/tenant_scope.py b/services/osquery-tls/app/security/tenant_scope.pyindex dc0fb8a6b..abe343959 100644--- a/services/osquery-tls/app/security/tenant_scope.py+++ b/services/osquery-tls/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/services/purple-team/app/security/service_auth.py b/services/purple-team/app/security/service_auth.pyindex 9bf04204a..6d83544f0 100644--- a/services/purple-team/app/security/service_auth.py+++ b/services/purple-team/app/security/service_auth.py@@ -31,7 +31,7 @@ ConfigurationWhen set and no token is configured, requests are allowed through so alocal ``docker compose up`` still works. This mirrors the single canonicaldev-mode flag used across the platform; it is asserted off in production by- ``tests/test_security_defaults.py``.+ ``services/api/tests/test_security_defaults.py``."""from __future__ import annotationsdiff --git a/services/purple-team/app/security/tenant_scope.py b/services/purple-team/app/security/tenant_scope.pyindex 8fe812cb3..9b8f1f77d 100644--- a/services/purple-team/app/security/tenant_scope.py+++ b/services/purple-team/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/services/threatintel/app/security/tenant_scope.py b/services/threatintel/app/security/tenant_scope.pyindex 906e37a3c..6d862aeba 100644--- a/services/threatintel/app/security/tenant_scope.py+++ b/services/threatintel/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/services/ueba/app/security/service_auth.py b/services/ueba/app/security/service_auth.pyindex 5ca5ab712..a2c7df12e 100644--- a/services/ueba/app/security/service_auth.py+++ b/services/ueba/app/security/service_auth.py@@ -31,7 +31,7 @@ ConfigurationWhen set and no token is configured, requests are allowed through so alocal ``docker compose up`` still works. This mirrors the single canonicaldev-mode flag used across the platform; it is asserted off in production by- ``tests/test_security_defaults.py``.+ ``services/api/tests/test_security_defaults.py``."""from __future__ import annotationsdiff --git a/services/ueba/app/security/tenant_scope.py b/services/ueba/app/security/tenant_scope.pyindex 69c32fa56..4a04c6c40 100644--- a/services/ueba/app/security/tenant_scope.py+++ b/services/ueba/app/security/tenant_scope.py@@ -2,8 +2,8 @@Vendored byte-identical into each Python service that needs it, following thesame convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.-Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the-build if they drift.+Keep the copies in sync — ``scripts/sync_vendored_tenant_scope.py --check``+fails the build if they drift.Why this exists---------------@@ -51,8 +51,9 @@ Configuration``AISOC_DEV_MODE``When set and *no* credential material is configured at all, requestsresolve to the demo tenant so a local ``docker compose up`` works. This is- the single canonical dev-mode flag; ``tests/test_security_defaults.py``- asserts no shortcut is reachable when it is unset.+ the single canonical dev-mode flag;+ ``services/api/tests/test_security_defaults.py`` asserts no shortcut is+ reachable when it is unset."""from __future__ import annotationsdiff --git a/tools/detection_import/__init__.py b/tools/detection_import/__init__.pyindex ec96f43e9..ad7caca4e 100644--- a/tools/detection_import/__init__.py+++ b/tools/detection_import/__init__.py@@ -4,5 +4,5 @@ Pulls detection content from upstream open-source projects (SigmaHQ, MITRE CAR,Chronicle, Splunk) and converts each rule into AiSOC's native YAML schema witha populated ``provenance`` block so every rule is traceable to its origin.-See ``tools/detection-import/README.md`` for usage.+See ``tools/detection_import/README.md`` for usage."""diff --git a/tools/detection_import/common.py b/tools/detection_import/common.pyindex e89ca0a13..7dd35b04b 100644--- a/tools/detection_import/common.py+++ b/tools/detection_import/common.py@@ -37,7 +37,7 @@ The native AiSOC schema (``detections/cloud/...`` etc.) uses ``match_when``blocks tied to ``RawAlert`` fields and is fixture-tested. Imported rules keepthe upstream ``detection`` block untouched so we can advertise honestattribution; the engine evaluates them through a Sigma-compat interpreter at-runtime (see ``services/fusion/detection_engine.py``).+runtime (see ``services/fusion/app/services/detection_engine.py``)."""from __future__ import annotations