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
Dead-letter visibility, and SLO alerts generated from the objectives (#713)
Beenu Aroradcfc51c62599
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2c6041422..7836c3f31 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -259,6 +259,16 @@ jobs:# genuinely dead service looks like an uninstrumented one. Also# checks datasource uids resolve: Grafana does not warn about a# dangling reference, the link just silently does nothing.+ # The SLO file declared availability and latency targets for all 17+ # services and no alert referenced any of them; the alerts used+ # thresholds no objective justified. Generating one from the other+ # makes the threshold traceable — an alert fires because an+ # objective is being missed, and changing the objective changes the+ # alert.+ - name: SLO alerts match the declared objectives+ run: |+ python -m pip install --quiet pyyaml+ python scripts/generate_slo_alerts.py --check- name: Grafana dashboards query metrics that existrun: python scripts/check_grafana_dashboards.py- name: Support bundle must not leakdiff --git a/docs/openapi.yaml b/docs/openapi.yamlindex fe751b973..082749e48 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -6396,6 +6396,63 @@ paths:title: Response Get Fleet Health Api V1 Health Fleet Getsecurity:- HTTPBearer: []+ /api/v1/health/dead-letters:+ get:+ tags:+ - health+ summary: Get Dead Letters+ description: 'Events the pipeline refused, and why.+++ Three DLQ implementations existed and none could answer this: one++ wrote a log line, one wrote to a Kafka topic with no consumer, one++ forgot on restart. Events were being dropped correctly and invisibly —++ and an invisible drop is indistinguishable from an event that never++ arrived, which is the worse of the two and the one nobody investigates.+++ Returns the breakdown by reason as well as the rows. A list of fifty++ dropped events is data; "forty-eight of them failed schema validation++ on the same topic" is a finding.'+ operationId: get_dead_letters_api_v1_health_dead_letters_get+ security:+ - HTTPBearer: []+ parameters:+ - name: limit+ in: query+ required: false+ schema:+ type: integer+ default: 50+ title: Limit+ - name: hours+ in: query+ required: false+ schema:+ type: integer+ default: 24+ title: Hours+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Response Get Dead Letters Api V1 Health Dead Letters Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/insights/soc:get:tags:diff --git a/docs/operations/observability.md b/docs/operations/observability.mdindex 948e6a37d..79920a1cd 100644--- a/docs/operations/observability.md+++ b/docs/operations/observability.md@@ -14,6 +14,28 @@ The objectives are targets, not measured SLIs — they define the **errorbudget** (`1 − availability_target` over a rolling 30 days) that the goldensignals below are measured against.+### Alerts are generated from the objectives++`infra/docker/alerts/slo.rules.yml` is produced by+`scripts/generate_slo_alerts.py` from `slos.yaml`, and a CI gate fails when+the two disagree. Before this, the SLO file declared targets nothing+alerted on while the alert rules used thresholds — a 5% error rate, a+2-second p95 — that corresponded to no objective in the file. Two numbers+meant to agree, maintained separately, will not agree for long.++Alerts are **burn-rate**, not instantaneous. A 99.9% target allows roughly+43 minutes of error a month; alerting the moment the rate exceeds 0.1%+pages on every transient blip. Fast burn (2% of the budget in an hour) is+a page. Slow burn (10% in six hours) is a ticket — not an outage, but the+shape that exhausts a month's budget without any single incident to point+at.++**Coverage is five of seventeen services**, because only five expose+`/metrics`. Generating rules for the other twelve would produce alerts+that can never fire, and an alert that can never fire reads as coverage+while providing none. The generator names the uncovered services on every+run rather than quietly skipping them.+## The four golden signalsFor each service we track the standard golden signals:@@ -27,7 +49,13 @@ For each service we track the standard golden signals:## Single trace across services-**Partial today.** `api`, `agents`, `ueba` and `honeytokens` are instrumented with **OpenTelemetry** and export via OTLP. `ingest` (Go) and `realtime` (TypeScript) are **not instrumented**, and they are the two ends of the Kafka spine — so a trace does not yet run unbroken from raw event to response action. Spans that are emitted carry the tenant and run/incident ids.+`api`, `agents`, `ueba`, `honeytokens`, `ingest` (Go) and `realtime` (TypeScript) are instrumented with **OpenTelemetry** and export via OTLP. The last two were the ends of the Kafka spine, so a trace used to begin at the API and stop at the pipeline boundary — which is where the interesting latency lives: an event that takes four seconds to become an alert is invisible if nothing spans the part that took four seconds.++All six share `OTEL_EXPORTER_OTLP_ENDPOINT` and propagate W3C `traceparent`, so a request continues as one trace rather than becoming several disconnected ones. Tracing is **off unless that variable is set**: emitting spans into a connection error is worse than emitting none, because it fills the logs and makes a missing trace ambiguous between "no span" and "no collector".++Sampling is parent-based at 5% by default (`OTEL_TRACES_SAMPLER_ARG`). Parent-based matters more than the ratio — a trace sampled at one service and re-decided at the next produces gaps that look like a service not participating.++Spans carry the tenant and run/incident ids.A collector now ships: `docker compose --profile monitoring up` starts an OpenTelemetry Collector on `otel-collector:4317` (the endpoint the services already default to) forwarding into Grafana Tempo, with Tempo wired into Grafana as a datasource alongside Prometheus. Previously no collector existed in any compose file, so out of the box every span went into a connection error — which is worse than no tracing, because the code looks instrumented and nobody can tell a missing span from a missing collector.diff --git a/infra/docker/alerts/slo.rules.yml b/infra/docker/alerts/slo.rules.ymlnew file mode 100644index 000000000..842ede529--- /dev/null+++ b/infra/docker/alerts/slo.rules.yml@@ -0,0 +1,204 @@+# GENERATED by scripts/generate_slo_alerts.py — do not edit.+#+# Thresholds come from docs/operations/slos.yaml. Editing them here makes+# the alert disagree with the objective it exists to enforce, which is the+# state this file was written to end: the SLOs declared targets nothing+# alerted on, and the alerts used thresholds no objective justified.+#+# Only services that expose /metrics are covered. An alert on a service+# Prometheus does not scrape can never fire, and an alert that can never+# fire reads as coverage.++groups:+- name: aisoc-slo+ rules:+ - alert: SloAgentsErrorBudgetFastBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-agents",status=~"5.."}[1h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-agents"}[1h])), 0.001)+ > 0.144000+ for: 5m+ labels:+ severity: page+ service: agents+ slo: availability+ annotations:+ summary: agents is burning its error budget fast+ description: At this rate agents consumes 2% of its 30-day error budget every 1h. Target is 99.000% availability (docs/operations/slos.yaml).+ - alert: SloAgentsErrorBudgetSlowBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-agents",status=~"5.."}[6h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-agents"}[6h])), 0.001)+ > 0.120000+ for: 30m+ labels:+ severity: ticket+ service: agents+ slo: availability+ annotations:+ summary: agents is steadily burning its error budget+ description: "Not an outage, which is why this is a ticket rather than a page \u2014 but at this rate agents exhausts its 30-day budget without any single incident to point at."+ - alert: SloAgentsLatencyBudgetMissed+ expr: |-+ histogram_quantile(0.95, sum by (le) (rate(aisoc_http_request_duration_seconds_bucket{job="aisoc-agents"}[30m])))+ > 120.000+ for: 15m+ labels:+ severity: ticket+ service: agents+ slo: latency+ annotations:+ summary: agents p95 latency is over its objective+ description: p95 above 120000 ms, the target in docs/operations/slos.yaml. Measured over 30 minutes so a single slow request does not page.+ - alert: SloApiErrorBudgetFastBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-api",status=~"5.."}[1h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-api"}[1h])), 0.001)+ > 0.014400+ for: 5m+ labels:+ severity: page+ service: api+ slo: availability+ annotations:+ summary: api is burning its error budget fast+ description: At this rate api consumes 2% of its 30-day error budget every 1h. Target is 99.900% availability (docs/operations/slos.yaml).+ - alert: SloApiErrorBudgetSlowBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-api",status=~"5.."}[6h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-api"}[6h])), 0.001)+ > 0.012000+ for: 30m+ labels:+ severity: ticket+ service: api+ slo: availability+ annotations:+ summary: api is steadily burning its error budget+ description: "Not an outage, which is why this is a ticket rather than a page \u2014 but at this rate api exhausts its 30-day budget without any single incident to point at."+ - alert: SloApiLatencyBudgetMissed+ expr: |-+ histogram_quantile(0.95, sum by (le) (rate(aisoc_http_request_duration_seconds_bucket{job="aisoc-api"}[30m])))+ > 0.300+ for: 15m+ labels:+ severity: ticket+ service: api+ slo: latency+ annotations:+ summary: api p95 latency is over its objective+ description: p95 above 300 ms, the target in docs/operations/slos.yaml. Measured over 30 minutes so a single slow request does not page.+ - alert: SloFusionErrorBudgetFastBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-fusion",status=~"5.."}[1h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-fusion"}[1h])), 0.001)+ > 0.014400+ for: 5m+ labels:+ severity: page+ service: fusion+ slo: availability+ annotations:+ summary: fusion is burning its error budget fast+ description: At this rate fusion consumes 2% of its 30-day error budget every 1h. Target is 99.900% availability (docs/operations/slos.yaml).+ - alert: SloFusionErrorBudgetSlowBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-fusion",status=~"5.."}[6h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-fusion"}[6h])), 0.001)+ > 0.012000+ for: 30m+ labels:+ severity: ticket+ service: fusion+ slo: availability+ annotations:+ summary: fusion is steadily burning its error budget+ description: "Not an outage, which is why this is a ticket rather than a page \u2014 but at this rate fusion exhausts its 30-day budget without any single incident to point at."+ - alert: SloFusionLatencyBudgetMissed+ expr: |-+ histogram_quantile(0.95, sum by (le) (rate(aisoc_http_request_duration_seconds_bucket{job="aisoc-fusion"}[30m])))+ > 0.500+ for: 15m+ labels:+ severity: ticket+ service: fusion+ slo: latency+ annotations:+ summary: fusion p95 latency is over its objective+ description: p95 above 500 ms, the target in docs/operations/slos.yaml. Measured over 30 minutes so a single slow request does not page.+ - alert: SloIngestErrorBudgetFastBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-ingest",status=~"5.."}[1h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-ingest"}[1h])), 0.001)+ > 0.014400+ for: 5m+ labels:+ severity: page+ service: ingest+ slo: availability+ annotations:+ summary: ingest is burning its error budget fast+ description: At this rate ingest consumes 2% of its 30-day error budget every 1h. Target is 99.900% availability (docs/operations/slos.yaml).+ - alert: SloIngestErrorBudgetSlowBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-ingest",status=~"5.."}[6h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-ingest"}[6h])), 0.001)+ > 0.012000+ for: 30m+ labels:+ severity: ticket+ service: ingest+ slo: availability+ annotations:+ summary: ingest is steadily burning its error budget+ description: "Not an outage, which is why this is a ticket rather than a page \u2014 but at this rate ingest exhausts its 30-day budget without any single incident to point at."+ - alert: SloIngestLatencyBudgetMissed+ expr: |-+ histogram_quantile(0.95, sum by (le) (rate(aisoc_http_request_duration_seconds_bucket{job="aisoc-ingest"}[30m])))+ > 0.200+ for: 15m+ labels:+ severity: ticket+ service: ingest+ slo: latency+ annotations:+ summary: ingest p95 latency is over its objective+ description: p95 above 200 ms, the target in docs/operations/slos.yaml. Measured over 30 minutes so a single slow request does not page.+ - alert: SloThreatintelErrorBudgetFastBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-threatintel",status=~"5.."}[1h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-threatintel"}[1h])), 0.001)+ > 0.144000+ for: 5m+ labels:+ severity: page+ service: threatintel+ slo: availability+ annotations:+ summary: threatintel is burning its error budget fast+ description: At this rate threatintel consumes 2% of its 30-day error budget every 1h. Target is 99.000% availability (docs/operations/slos.yaml).+ - alert: SloThreatintelErrorBudgetSlowBurn+ expr: |-+ sum(rate(aisoc_http_requests_total{job="aisoc-threatintel",status=~"5.."}[6h]))+ / clamp_min(sum(rate(aisoc_http_requests_total{job="aisoc-threatintel"}[6h])), 0.001)+ > 0.120000+ for: 30m+ labels:+ severity: ticket+ service: threatintel+ slo: availability+ annotations:+ summary: threatintel is steadily burning its error budget+ description: "Not an outage, which is why this is a ticket rather than a page \u2014 but at this rate threatintel exhausts its 30-day budget without any single incident to point at."+ - alert: SloThreatintelLatencyBudgetMissed+ expr: |-+ histogram_quantile(0.95, sum by (le) (rate(aisoc_http_request_duration_seconds_bucket{job="aisoc-threatintel"}[30m])))+ > 1.000+ for: 15m+ labels:+ severity: ticket+ service: threatintel+ slo: latency+ annotations:+ summary: threatintel p95 latency is over its objective+ description: p95 above 1000 ms, the target in docs/operations/slos.yaml. Measured over 30 minutes so a single slow request does not page.diff --git a/scripts/generate_slo_alerts.py b/scripts/generate_slo_alerts.pynew file mode 100644index 000000000..800f1a818--- /dev/null+++ b/scripts/generate_slo_alerts.py@@ -0,0 +1,258 @@+#!/usr/bin/env python3+"""Generate Prometheus alerts from the SLO file, and gate the two together.++`docs/operations/slos.yaml` declares an availability target and a p95+latency budget for all 17 services. The alert rules alongside it use+hardcoded thresholds picked independently — a 5% error rate, a 2-second+p95 — that correspond to no objective in the file. So the SLOs were, as+the plan put it, objectives nothing alerts on, and the alerts were numbers+nothing justifies.++Generating one from the other makes the threshold traceable: an alert+fires because an objective is being missed, and changing the objective+changes the alert. Two numbers that are supposed to agree and are+maintained separately will not agree for long.++**Only scraped services get alerts.** Five of seventeen expose `/metrics`;+generating for all seventeen would produce twelve alerts that can never+fire, and an alert that can never fire is worse than none — it reads as+coverage. The uncovered services are reported instead.++**Burn-rate, not instantaneous.** A 99.9% target allows roughly 43 minutes+of error per month. Alerting the moment the rate exceeds 0.1% pages on+every transient blip; alerting on how fast the month's budget is being+consumed pages when the objective is actually at risk. Fast burn (2% of+budget in an hour) is a page; slow burn (10% in six hours) is a ticket.++Run: python3 scripts/generate_slo_alerts.py [--check]+"""++from __future__ import annotations++import argparse+import re+import sys+from pathlib import Path++try:+ import yaml+except ImportError: # pragma: no cover+ print("PyYAML is required: pip install pyyaml", file=sys.stderr)+ raise SystemExit(2) from None++REPO_ROOT = Path(__file__).resolve().parent.parent+SLOS = REPO_ROOT / "docs" / "operations" / "slos.yaml"+PROMETHEUS = REPO_ROOT / "infra" / "docker" / "prometheus.yml"+OUTPUT = REPO_ROOT / "infra" / "docker" / "alerts" / "slo.rules.yml"++HEADER = """# GENERATED by scripts/generate_slo_alerts.py — do not edit.+#+# Thresholds come from docs/operations/slos.yaml. Editing them here makes+# the alert disagree with the objective it exists to enforce, which is the+# state this file was written to end: the SLOs declared targets nothing+# alerted on, and the alerts used thresholds no objective justified.+#+# Only services that expose /metrics are covered. An alert on a service+# Prometheus does not scrape can never fire, and an alert that can never+# fire reads as coverage.+"""++#: Burn-rate windows. The pair is deliberate: fast burn catches an outage,+#: slow burn catches a persistent low-grade failure that would exhaust the+#: month without ever looking like an incident.+FAST_WINDOW = "1h"+FAST_BUDGET_FRACTION = 0.02+SLOW_WINDOW = "6h"+SLOW_BUDGET_FRACTION = 0.10+++class _BlockDumper(yaml.SafeDumper):+ """Emit multi-line strings as literal blocks.++ A PromQL expression escaped into a quoted scalar — `"sum(rate(...))\n+ / clamp_min(...)"` — is unreadable, and these are rules an operator+ reads at three in the morning to work out why they were paged.+ """+++def _block_str(dumper: yaml.SafeDumper, value: str):+ style = "|" if "\n" in value else None+ return dumper.represent_scalar("tag:yaml.org,2002:str", value, style=style)+++_BlockDumper.add_representer(str, _block_str)+++def scraped_jobs() -> set[str]:+ """Service names Prometheus actually scrapes, from the job names."""+ if not PROMETHEUS.exists():+ return set()+ jobs: set[str] = set()+ for match in re.finditer(r"^\s*-?\s*job_name:\s*(\S+)", PROMETHEUS.read_text(), re.M):+ job = match.group(1).strip().strip("\"'")+ jobs.add(job.removeprefix("aisoc-"))+ return jobs+++def burn_rate_threshold(availability_target: float, budget_fraction: float, window_hours: float) -> float:+ """Error rate that consumes `budget_fraction` of a 30-day budget in `window_hours`.++ Standard multi-window burn rate: the budget is+ ``1 - target`` over 30 days, so consuming a fraction of it in a+ shorter window means erroring at a proportionally higher rate.+ """+ error_budget = 1.0 - availability_target+ month_hours = 30 * 24+ return error_budget * budget_fraction * (month_hours / window_hours)+++def rules_for(service: str, slo: dict) -> list[dict]:+ target = float(slo.get("availability_target", 0.999))+ latency_ms = slo.get("latency_p95_ms")+ job = f"aisoc-{service}"++ fast = burn_rate_threshold(target, FAST_BUDGET_FRACTION, 1)+ slow = burn_rate_threshold(target, SLOW_BUDGET_FRACTION, 6)++ rules: list[dict] = [+ {+ "alert": f"Slo{service.title().replace('-', '')}ErrorBudgetFastBurn",+ "expr": (+ f'sum(rate(aisoc_http_requests_total{{job="{job}",status=~"5.."}}[{FAST_WINDOW}]))\n'+ f' / clamp_min(sum(rate(aisoc_http_requests_total{{job="{job}"}}[{FAST_WINDOW}])), 0.001)\n'+ f" > {fast:.6f}"+ ),+ "for": "5m",+ "labels": {"severity": "page", "service": service, "slo": "availability"},+ "annotations": {+ "summary": f"{service} is burning its error budget fast",+ "description": (+ f"At this rate {service} consumes "+ f"{FAST_BUDGET_FRACTION:.0%} of its 30-day error budget "+ f"every {FAST_WINDOW}. Target is {target:.3%} availability "+ f"(docs/operations/slos.yaml)."+ ),+ },+ },+ {+ "alert": f"Slo{service.title().replace('-', '')}ErrorBudgetSlowBurn",+ "expr": (+ f'sum(rate(aisoc_http_requests_total{{job="{job}",status=~"5.."}}[{SLOW_WINDOW}]))\n'+ f' / clamp_min(sum(rate(aisoc_http_requests_total{{job="{job}"}}[{SLOW_WINDOW}])), 0.001)\n'+ f" > {slow:.6f}"+ ),+ "for": "30m",+ "labels": {"severity": "ticket", "service": service, "slo": "availability"},+ "annotations": {+ "summary": f"{service} is steadily burning its error budget",+ "description": (+ f"Not an outage, which is why this is a ticket rather than "+ f"a page — but at this rate {service} exhausts its 30-day "+ f"budget without any single incident to point at."+ ),+ },+ },+ ]++ if latency_ms:+ rules.append(+ {+ "alert": f"Slo{service.title().replace('-', '')}LatencyBudgetMissed",+ "expr": (+ f"histogram_quantile(0.95, sum by (le) "+ f'(rate(aisoc_http_request_duration_seconds_bucket{{job="{job}"}}[30m])))\n'+ f" > {float(latency_ms) / 1000:.3f}"+ ),+ "for": "15m",+ "labels": {"severity": "ticket", "service": service, "slo": "latency"},+ "annotations": {+ "summary": f"{service} p95 latency is over its objective",+ "description": (+ f"p95 above {latency_ms} ms, the target in "+ f"docs/operations/slos.yaml. Measured over 30 minutes so "+ f"a single slow request does not page."+ ),+ },+ }+ )++ return rules+++def build() -> tuple[str, list[str], list[str]]:+ """Returns (yaml text, covered services, services with no metrics)."""+ data = yaml.safe_load(SLOS.read_text(encoding="utf-8")) or {}+ services = data.get("services", {})+ jobs = scraped_jobs()++ covered: list[str] = []+ uncovered: list[str] = []+ rules: list[dict] = []++ for service, entry in sorted(services.items()):+ slo = (entry or {}).get("slo") or entry or {}+ if "availability_target" not in slo:+ # An exempt service declares no objective, so there is nothing+ # to alert on. Not a gap.+ continue+ if service not in jobs:+ uncovered.append(service)+ continue+ covered.append(service)+ rules.extend(rules_for(service, slo))++ document = {"groups": [{"name": "aisoc-slo", "rules": rules}]}+ text = HEADER + "\n" + yaml.dump(document, Dumper=_BlockDumper, sort_keys=False, width=1000)+ return text, covered, uncovered+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--check", action="store_true")+ args = parser.parse_args(argv)++ if not SLOS.exists():+ print("slo-alerts: docs/operations/slos.yaml not found", file=sys.stderr)+ return 2++ text, covered, uncovered = build()++ if not covered:+ print(+ "slo-alerts: no service with an SLO is scraped, so no alert could " "reference an objective",+ file=sys.stderr,+ )+ return 1++ if args.check:+ if not OUTPUT.exists():+ print(+ f"SLO ALERT GATE FAILED: {OUTPUT.relative_to(REPO_ROOT)} is " f"missing.\n Run: python3 scripts/generate_slo_alerts.py",+ file=sys.stderr,+ )+ return 1+ if OUTPUT.read_text(encoding="utf-8") != text:+ print(+ "SLO ALERT GATE FAILED: the generated alerts no longer match "+ "docs/operations/slos.yaml.\n"+ " An objective changed and its alert did not, so the alert "+ "now enforces a number nothing declares.\n"+ " Run: python3 scripts/generate_slo_alerts.py",+ file=sys.stderr,+ )+ return 1+ print(f"slo-alerts: OK — {len(covered)} service(s) alert against their " f"declared objectives")+ if uncovered:+ print(f" no alerts for {len(uncovered)} service(s) with an SLO but no " f"/metrics: {', '.join(uncovered)}")+ return 0++ OUTPUT.parent.mkdir(parents=True, exist_ok=True)+ OUTPUT.write_text(text, encoding="utf-8")+ print(f"slo-alerts: wrote {len(covered)} service(s) to {OUTPUT.relative_to(REPO_ROOT)}")+ if uncovered:+ print(f" skipped (SLO declared, no /metrics): {', '.join(uncovered)}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/api/app/api/v1/endpoints/health.py b/services/api/app/api/v1/endpoints/health.pyindex 65bf946ed..21a44a226 100644--- a/services/api/app/api/v1/endpoints/health.py+++ b/services/api/app/api/v1/endpoints/health.py@@ -78,7 +78,7 @@ from datetime import UTC, datetime, timedeltafrom typing import Anyfrom fastapi import APIRouter-from sqlalchemy import and_, func, select+from sqlalchemy import and_, func, select, textfrom app.api.v1.deps import AuthUser, DBSessionfrom app.api.v1.endpoints.metrics import PipelineHealth, PipelineStage@@ -533,3 +533,88 @@ async def get_fleet_health("""rows = (await db.execute(select(Connector).where(Connector.tenant_id == user.tenant_id))).scalars().all()return assess_fleet(list(rows)).to_dict()++[email protected]("/dead-letters")+async def get_dead_letters(+ user: AuthUser,+ db: DBSession,+ limit: int = 50,+ hours: int = 24,+) -> dict[str, Any]:+ """Events the pipeline refused, and why.++ Three DLQ implementations existed and none could answer this: one+ wrote a log line, one wrote to a Kafka topic with no consumer, one+ forgot on restart. Events were being dropped correctly and invisibly —+ and an invisible drop is indistinguishable from an event that never+ arrived, which is the worse of the two and the one nobody investigates.++ Returns the breakdown by reason as well as the rows. A list of fifty+ dropped events is data; "forty-eight of them failed schema validation+ on the same topic" is a finding.+ """+ since = datetime.now(UTC) - timedelta(hours=max(1, min(hours, 720)))+ capped = max(1, min(limit, 500))++ rows = (+ (+ await db.execute(+ text(+ """+ SELECT id, topic, reason, schema_version, payload_excerpt,+ source_event_id, occurred_at, acknowledged_at+ FROM aisoc_dead_letters+ WHERE tenant_id = :tid AND occurred_at >= :since+ ORDER BY occurred_at DESC+ LIMIT :lim+ """+ ),+ {"tid": user.tenant_id, "since": since, "lim": capped},+ )+ )+ .mappings()+ .all()+ )++ by_reason = (+ (+ await db.execute(+ text(+ """+ SELECT reason, count(*) AS n+ FROM aisoc_dead_letters+ WHERE tenant_id = :tid AND occurred_at >= :since+ GROUP BY reason+ ORDER BY n DESC+ """+ ),+ {"tid": user.tenant_id, "since": since},+ )+ )+ .mappings()+ .all()+ )++ total = sum(int(r["n"]) for r in by_reason)+ return {+ "window_hours": hours,+ "total": total,+ # Present even when zero, and labelled: "no dead letters" is a+ # real answer and should not look like a broken panel.+ "by_reason": [{"reason": r["reason"], "count": int(r["n"])} for r in by_reason],+ "truncated": len(rows) >= capped,+ "dead_letters": [+ {+ "id": str(r["id"]),+ "topic": r["topic"],+ "reason": r["reason"],+ "schema_version": r["schema_version"],+ "payload_excerpt": r["payload_excerpt"],+ "source_event_id": r["source_event_id"],+ "occurred_at": r["occurred_at"].isoformat() if r["occurred_at"] else None,+ "acknowledged": r["acknowledged_at"] is not None,+ }+ for r in rows+ ],+ }diff --git a/services/api/migrations/053_dead_letters.sql b/services/api/migrations/053_dead_letters.sqlnew file mode 100644index 000000000..c4f8d9824--- /dev/null+++ b/services/api/migrations/053_dead_letters.sql@@ -0,0 +1,56 @@+-- Dead letters, made visible.+--+-- The fusion consumer routes poison events to a dead-letter queue and has+-- done since the DLQ landed. Nothing ever read it back: `LoggingDLQ` writes+-- a log line, `KafkaDLQ` writes to a topic with no consumer, and+-- `InMemoryDLQ` forgets on restart. So an operator could not answer "what+-- did we drop, and why" — which is the one question a dead-letter queue+-- exists to answer.+--+-- Dropped events are rare by construction (a poison message is a bug, not+-- traffic), so this table stays small and a plain B-tree index is enough.+-- It is deliberately not partitioned: partitioning a table that should have+-- tens of rows a week optimises for a failure mode that would itself be the+-- incident.++CREATE TABLE IF NOT EXISTS aisoc_dead_letters (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),++ -- Nullable because a message can be rejected *before* its tenant is+ -- known — a malformed envelope has no tenant, and recording a guess+ -- would put another tenant's name on someone else's bad data.+ tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,++ topic TEXT NOT NULL,+ reason TEXT NOT NULL,+ schema_version TEXT NOT NULL DEFAULT 'unknown',++ -- An excerpt, never the whole payload. The payload is what was rejected,+ -- so it is untrusted by definition and may be large or hostile; storing+ -- all of it turns this table into an unbounded sink for exactly the+ -- content the pipeline refused.+ payload_excerpt TEXT NOT NULL DEFAULT '',+ source_event_id TEXT,++ occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),++ -- Triage state. A dead letter nobody acknowledged is different from one+ -- someone looked at and decided was expected.+ acknowledged_at TIMESTAMPTZ,+ acknowledged_by TEXT+);++-- The query an operator actually runs: recent drops for my tenant, newest+-- first.+CREATE INDEX IF NOT EXISTS idx_dead_letters_tenant_time+ ON aisoc_dead_letters (tenant_id, occurred_at DESC);++-- And the aggregate that turns a list into a finding: which reason is+-- responsible for most of them.+CREATE INDEX IF NOT EXISTS idx_dead_letters_reason+ ON aisoc_dead_letters (reason, occurred_at DESC);++COMMENT ON TABLE aisoc_dead_letters IS+ 'Events the pipeline refused, with the reason. Written by services/fusion; '+ 'read by GET /api/v1/health/dead-letters. Subject to the tenant retention '+ 'policy like any other tenant-scoped data.';diff --git a/services/fusion/app/main.py b/services/fusion/app/main.pyindex 7ff6e749d..fd7e4ba3c 100644--- a/services/fusion/app/main.py+++ b/services/fusion/app/main.py@@ -17,6 +17,7 @@ from app.services.confidence import ConfidenceScorerfrom app.services.correlator import Correlatorfrom app.services.deduplicator import Deduplicatorfrom app.services.detection_engine import DetectionEngine+from app.services.dlq_sink import PostgresDLQfrom app.services.entity_risk import EntityRiskEnginefrom app.services.fusion_engine import FusionEnginefrom app.services.lake_writer import LakeWriter@@ -92,9 +93,20 @@ async def lifespan(app: FastAPI):detector = DetectionEngine() if settings.detection_engine_enabled else None# Wave 2 — windowed detections share the fusion Redis for sliding-window state.windowed_detector = WindowedDetectionEngine(redis_client) if settings.windowed_detection_enabled else None+ # Dead letters go to Postgres so they can be read back. Until now the+ # worker defaulted to LoggingDLQ, so a dropped event produced a log+ # line and nothing else — and an invisible drop is indistinguishable+ # from an event that never arrived.+ #+ # The pool is passed as a callable because `sink.start()` opens it+ # during `worker.start()`, after this point; capturing it eagerly would+ # capture None and drop every dead letter.+ dlq = PostgresDLQ(lambda: sink._pool) if sink is not None else None+worker = FusionWorker(engine,sink=sink,+ dlq=dlq,lake=lake,detector=detector,windowed_detector=windowed_detector,diff --git a/services/fusion/app/services/dlq_sink.py b/services/fusion/app/services/dlq_sink.pynew file mode 100644index 000000000..7c9d38983--- /dev/null+++ b/services/fusion/app/services/dlq_sink.py@@ -0,0 +1,135 @@+"""A dead-letter queue an operator can actually read.++Three DLQ implementations existed and none of them could answer the+question a DLQ exists for. `LoggingDLQ` writes a log line, which is+findable only if you already know to look. `KafkaDLQ` writes to+`aisoc.alerts.dlq`, which has no consumer. `InMemoryDLQ` forgets on+restart.++So events were being dropped correctly and invisibly — and an invisible+drop is indistinguishable from an event that never arrived, which is the+worse of the two possibilities and the one nobody investigates.++This persists them. Two properties matter more than the writing:++**A DLQ that fails must not take the pipeline with it.** The whole point+of routing a poison message aside is to keep consuming; if recording that+decision can raise, the DLQ becomes a second way for one bad event to stop+everything. Every failure here is logged and swallowed, which is the one+place in this codebase where swallowing is the correct behaviour.++**The payload is truncated, never stored whole.** It is untrusted by+definition — it is the thing the pipeline refused — and may be large or+hostile. Storing all of it makes this table an unbounded sink for exactly+the content that was rejected.+"""++from __future__ import annotations++from collections.abc import Callable++import asyncpg+import structlog++from app.services.dlq import DeadLetter, DeadLetterQueue++logger = structlog.get_logger(__name__)++#: Characters of payload kept. Enough to recognise the shape and find the+#: producer; far short of enough to reconstruct the event, which is+#: deliberate — this is a triage record, not a replay buffer.+MAX_EXCERPT = 2000++_INSERT_SQL = """+INSERT INTO aisoc_dead_letters+ (tenant_id, topic, reason, schema_version, payload_excerpt, source_event_id)+VALUES ($1, $2, $3, $4, $5, $6)+"""+++class PostgresDLQ(DeadLetterQueue):+ """Persist rejected messages so they can be triaged.++ Takes a provider rather than a pool, because the connection pool is+ opened during worker startup — after this is constructed. Capturing it+ eagerly would capture ``None`` and silently drop every dead letter,+ which is the failure this class exists to end.++ A provider *always*, never "a pool or a provider": telling the two+ apart with ``callable()`` is wrong for anything with ``__call__``,+ which includes every mock, and a constructor whose behaviour depends+ on duck-typing its own argument is one that fails differently in+ tests than in production. Callers with a concrete pool pass+ ``lambda: pool``.+ """++ def __init__(self, pool_provider: Callable[[], asyncpg.Pool | None]) -> None:+ self._pool_provider = pool_provider++ def _pool_now(self) -> asyncpg.Pool | None:+ return self._pool_provider()++ async def record(self, letter: DeadLetter) -> None:+ excerpt = (letter.payload_excerpt or "")[:MAX_EXCERPT]+ tenant_id = _as_uuid(letter.tenant_id)++ pool = self._pool_now()+ if pool is None:+ # The sink never opened, so there is nowhere to write. Logged+ # at warning rather than silently skipped: a DLQ that records+ # nothing looks exactly like a pipeline dropping nothing.+ logger.warning(+ "dlq.no_pool",+ topic=letter.topic,+ reason=letter.reason,+ )+ return++ try:+ async with pool.acquire() as conn:+ await conn.execute(+ _INSERT_SQL,+ tenant_id,+ letter.topic,+ letter.reason,+ letter.schema_version,+ excerpt,+ letter.source_event_id,+ )+ except Exception as exc: # noqa: BLE001 - see the module docstring+ # Losing the record of a dropped event is bad. Stopping the+ # consumer because we could not record it is worse: one poison+ # message would then halt the pipeline, which is precisely the+ # outcome the DLQ exists to prevent.+ logger.warning(+ "dlq.persist_failed",+ topic=letter.topic,+ reason=letter.reason,+ error=str(exc),+ )+ return++ logger.info(+ "dlq.recorded",+ topic=letter.topic,+ reason=letter.reason,+ tenant_id=letter.tenant_id,+ )+++def _as_uuid(value: str | None):+ """Parse a tenant id, or None.++ A malformed envelope can carry a tenant field that is not a uuid.+ Rejecting the whole record over it would lose the dead letter entirely+ — and the dead letter is the evidence that something is producing+ malformed envelopes.+ """+ if not value:+ return None+ import uuid # noqa: PLC0415 - only needed on the failure path++ try:+ return uuid.UUID(str(value))+ except (ValueError, AttributeError, TypeError):+ return Nonediff --git a/services/fusion/tests/test_dlq_sink.py b/services/fusion/tests/test_dlq_sink.pynew file mode 100644index 000000000..7b12b0c52--- /dev/null+++ b/services/fusion/tests/test_dlq_sink.py@@ -0,0 +1,133 @@+"""A dead-letter queue that can be read, and that cannot stop the pipeline.++Three DLQ implementations existed and none could answer the question a DLQ+exists for. One wrote a log line, one wrote to a Kafka topic with no+consumer, one forgot on restart. Events were dropped correctly and+invisibly — and an invisible drop is indistinguishable from an event that+never arrived, which is the worse possibility and the one nobody+investigates.++The tests are mostly about the failure paths, because that is where a DLQ+earns its place: recording a dropped event must never become a second way+for one bad message to halt consumption.+"""++from __future__ import annotations++import uuid+from unittest.mock import AsyncMock, MagicMock++import pytest+from app.services.dlq import DeadLetter+from app.services.dlq_sink import MAX_EXCERPT, PostgresDLQ, _as_uuid+++def _pool(execute: AsyncMock | None = None) -> MagicMock:+ conn = AsyncMock()+ conn.execute = execute or AsyncMock()+ pool = MagicMock()+ acquire = MagicMock()+ acquire.__aenter__ = AsyncMock(return_value=conn)+ acquire.__aexit__ = AsyncMock(return_value=False)+ pool.acquire = MagicMock(return_value=acquire)+ pool._conn = conn+ return pool+++def _letter(**overrides) -> DeadLetter:+ base = {+ "topic": "aisoc.raw_events",+ "reason": "schema_validation_failed",+ "schema_version": "v1",+ "payload_excerpt": '{"bad": true}',+ "source_event_id": "evt-1",+ "tenant_id": str(uuid.uuid4()),+ }+ base.update(overrides)+ return DeadLetter(**base)+++class TestRecording:+ @pytest.mark.asyncio+ async def test_writes_the_letter(self) -> None:+ pool = _pool()+ await PostgresDLQ(lambda: pool).record(_letter())+ pool._conn.execute.assert_awaited_once()+ args = pool._conn.execute.await_args.args+ assert "aisoc_dead_letters" in args[0]+ assert args[2] == "aisoc.raw_events"+ assert args[3] == "schema_validation_failed"++ @pytest.mark.asyncio+ async def test_the_payload_is_truncated(self) -> None:+ """The payload is untrusted by definition — it is the thing the+ pipeline refused — so storing all of it makes this table an+ unbounded sink for exactly the content that was rejected."""+ pool = _pool()+ await PostgresDLQ(lambda: pool).record(_letter(payload_excerpt="x" * 100_000))+ excerpt = pool._conn.execute.await_args.args[5]+ assert len(excerpt) == MAX_EXCERPT++ @pytest.mark.asyncio+ async def test_no_pool_yet_is_logged_not_crashed(self) -> None:+ """The pool opens during worker startup, after the DLQ is built.+ A dead letter arriving in that window must not raise."""+ await PostgresDLQ(lambda: None).record(_letter())++ @pytest.mark.asyncio+ async def test_a_callable_pool_is_resolved_at_record_time(self) -> None:+ """Resolving eagerly would capture None and silently drop every+ dead letter — the exact failure this class exists to end."""+ pool = _pool()+ holder: list = [None]+ sink = PostgresDLQ(lambda: holder[0])+ holder[0] = pool+ await sink.record(_letter())+ pool._conn.execute.assert_awaited_once()+++class TestItCannotStopThePipeline:+ @pytest.mark.asyncio+ async def test_a_database_failure_is_swallowed(self) -> None:+ """The whole point of routing a poison message aside is to keep+ consuming. If recording that decision can raise, the DLQ becomes a+ second way for one bad event to halt everything."""+ pool = _pool(AsyncMock(side_effect=RuntimeError("connection refused")))+ await PostgresDLQ(lambda: pool).record(_letter()) # must not raise++ @pytest.mark.asyncio+ async def test_an_unacquirable_pool_is_swallowed(self) -> None:+ pool = MagicMock()+ pool.acquire = MagicMock(side_effect=RuntimeError("pool exhausted"))+ await PostgresDLQ(lambda: pool).record(_letter()) # must not raise+++class TestTenantParsing:+ @pytest.mark.parametrize("bad", ["", None, "not-a-uuid", "12345", "default"])+ def test_a_malformed_tenant_becomes_null_rather_than_losing_the_record(self, bad: str | None) -> None:+ """A malformed envelope can carry a tenant field that is not a+ uuid. Rejecting the record over it would lose the dead letter —+ and the dead letter is the evidence that something is producing+ malformed envelopes."""+ assert _as_uuid(bad) is None++ def test_a_valid_tenant_is_preserved(self) -> None:+ tid = uuid.uuid4()+ assert _as_uuid(str(tid)) == tid++ @pytest.mark.asyncio+ async def test_a_letter_with_no_tenant_is_still_recorded(self) -> None:+ """A message can be rejected before its tenant is known. Recording+ a guess would put another tenant's name on someone else's bad+ data."""+ pool = _pool()+ await PostgresDLQ(lambda: pool).record(_letter(tenant_id=None))+ assert pool._conn.execute.await_args.args[1] is None+++def test_it_implements_the_queue_interface() -> None:+ """So it can be swapped in wherever the consumer builds its DLQ,+ rather than becoming a fourth implementation nothing uses."""+ from app.services.dlq import DeadLetterQueue++ assert issubclass(PostgresDLQ, DeadLetterQueue)diff --git a/services/ingest/go.mod b/services/ingest/go.modindex c063c9a1a..576cb2244 100644--- a/services/ingest/go.mod+++ b/services/ingest/go.mod@@ -12,12 +12,22 @@ require (github.com/redis/go-redis/v9 v9.22.0github.com/rs/zerolog v1.35.1github.com/segmentio/kafka-go v0.4.51+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0+ go.opentelemetry.io/otel v1.46.0+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0+ go.opentelemetry.io/otel/sdk v1.46.0+ go.opentelemetry.io/otel/trace v1.46.0gopkg.in/yaml.v3 v3.0.1)require (github.com/beorn7/perks v1.0.1 // indirect+ github.com/cenkalti/backoff/v5 v5.0.3 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirect+ github.com/felixge/httpsnoop v1.1.0 // indirect+ github.com/go-logr/logr v1.4.4 // indirect+ github.com/go-logr/stdr v1.2.2 // indirect+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirectgithub.com/jackc/pgpassfile v1.0.0 // indirectgithub.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirectgithub.com/jackc/puddle/v2 v2.2.2 // indirect@@ -31,9 +41,17 @@ require (github.com/prometheus/common v0.70.1 // indirectgithub.com/prometheus/procfs v0.21.1 // indirectgithub.com/rogpeppe/go-internal v1.15.0 // indirect+ go.opentelemetry.io/auto/sdk v1.2.1 // indirect+ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect+ go.opentelemetry.io/otel/metric v1.46.0 // indirect+ go.opentelemetry.io/proto/otlp v1.11.0 // indirectgo.uber.org/atomic v1.11.0 // indirect+ golang.org/x/net v0.58.0 // indirectgolang.org/x/sync v0.22.0 // indirectgolang.org/x/sys v0.47.0 // indirect- golang.org/x/text v0.40.0 // indirect- google.golang.org/protobuf v1.36.11 // indirect+ golang.org/x/text v0.41.0 // indirect+ google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect+ google.golang.org/grpc v1.83.1 // indirect+ google.golang.org/protobuf v1.36.12 // indirect)diff --git a/services/ingest/go.sum b/services/ingest/go.sumindex d608484cb..46aa737a6 100644--- a/services/ingest/go.sum+++ b/services/ingest/go.sum@@ -4,20 +4,31 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=+github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=+github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=+github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=+github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=+github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=@@ -30,8 +41,8 @@ github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJngithub.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=-github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=-github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=@@ -46,7 +57,6 @@ github.com/neo4j/neo4j-go-driver/v5 v5.28.4 h1:7toxehVcYkZbyxV4W3Ib9VcnyRBQPucF+github.com/neo4j/neo4j-go-driver/v5 v5.28.4/go.mod h1:Vff8OwT7QpLm7L2yYr85XNWe9Rbqlbeb9asNXJTHO4k=github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0=github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=@@ -67,8 +77,8 @@ github.com/segmentio/kafka-go v0.4.51/go.mod h1:Y1gn60kzLEEaW28YshXyk2+VCUKbJ3Qrgithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=-github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=-github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=@@ -77,23 +87,53 @@ github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=+go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=+go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 h1:w53CDeOA/Kurp7yRsegSr6pbbr759dOvJ+yNmWM6Hxs=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0/go.mod h1:BOmGMCbAtvcJiSJ+hLuhgPLdDbimnraSl8irz3iY8sY=+go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=+go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=+go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=+go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=+go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=+go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=+go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=+go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=+go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=+go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=-golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=-golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=+golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=+golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=-golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=-golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=+golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=+google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 h1:ax2KzoSRIZU/M0cIxri3pKxy99vniH1PVxWC6si/eZI=+google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688/go.mod h1:1RJ9BQGyNdZwkGc1eTqkErfRZ6RJyYPHZo73BZ1vQqI=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 h1:cYNAzI2sUwhmCcoj9TxvihSrqsxt6uIkj3rDRhSDmW4=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=+google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y=+google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=diff --git a/services/ingest/internal/server/server.go b/services/ingest/internal/server/server.goindex 09deaca1d..73a41ba42 100644--- a/services/ingest/internal/server/server.go+++ b/services/ingest/internal/server/server.go@@ -18,6 +18,7 @@ import ("github.com/go-chi/cors""github.com/prometheus/client_golang/prometheus/promhttp""github.com/rs/zerolog/log"+ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp")// resolveCORSOrigins mirrors the shared Python helper in services/api/app/core/cors.py:@@ -74,6 +75,14 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler, gr// Middlewarer.Use(middleware.RequestID)r.Use(middleware.RealIP)+ // Continues a trace started upstream rather than beginning a new one:+ // the propagator reads W3C traceparent, so an API request that reaches+ // ingest stays one trace instead of becoming two disconnected ones.+ // No-op when tracing is disabled, since the global provider is a+ // no-op provider in that case.+ r.Use(func(next http.Handler) http.Handler {+ return otelhttp.NewHandler(next, "ingest")+ })r.Use(middleware.Recoverer)r.Use(middleware.Timeout(30 * time.Second))// Allow-list is resolved from AISOC_CORS_ORIGINS (canonical) / CORS_ORIGINSdiff --git a/services/ingest/internal/telemetry/telemetry.go b/services/ingest/internal/telemetry/telemetry.gonew file mode 100644index 000000000..3252ae78b--- /dev/null+++ b/services/ingest/internal/telemetry/telemetry.go@@ -0,0 +1,173 @@+// Package telemetry wires OpenTelemetry tracing for the ingest service.+//+// `api`, `agents`, `ueba` and `honeytokens` were instrumented; `ingest`+// (Go) and `realtime` (TypeScript) were not — and those two are the ends+// of the Kafka spine. A trace therefore began at the API and stopped at+// the pipeline boundary, which is precisely where the interesting latency+// is: an event that takes four seconds to become an alert is invisible if+// nothing spans the part that took four seconds.+//+// Two decisions worth stating.+//+// Tracing is off unless an endpoint is configured. Defaulting it on sent+// every span into a connection error on deployments with no collector,+// which fills the logs and makes a missing trace ambiguous between "no+// span" and "no collector" — the failure the compose collector comment+// already records.+//+// Shutdown flushes with a bounded timeout. An unflushed exporter drops+// the spans from the final seconds before a restart, and those are+// disproportionately the ones someone is looking for.+package telemetry++import (+ "context"+ "os"+ "strconv"+ "strings"+ "time"++ "go.opentelemetry.io/otel"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"+ "go.opentelemetry.io/otel/propagation"+ "go.opentelemetry.io/otel/sdk/resource"+ sdktrace "go.opentelemetry.io/otel/sdk/trace"+ semconv "go.opentelemetry.io/otel/semconv/v1.26.0"+ "go.opentelemetry.io/otel/trace"+ "go.opentelemetry.io/otel/trace/noop"+)++const defaultServiceName = "aisoc-ingest"++// Shutdown flushes pending spans. Always non-nil, so a caller never has to+// nil-check before deferring it.+type Shutdown func(context.Context) error++// Setup configures the global tracer provider from the environment.+//+// Returns a no-op shutdown when tracing is disabled, so the caller's+// `defer shutdown(ctx)` is unconditional and cannot be forgotten on the+// disabled path.+func Setup(ctx context.Context) (Shutdown, error) {+ endpoint := strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"))+ if endpoint == "" {+ // Not an error. A deployment without a collector is a supported+ // configuration, and emitting spans nobody collects is worse than+ // emitting none.+ otel.SetTracerProvider(noop.NewTracerProvider())+ return func(context.Context) error { return nil }, nil+ }++ exporter, err := otlptracegrpc.New(+ ctx,+ otlptracegrpc.WithEndpoint(stripScheme(endpoint)),+ // Plaintext to an in-cluster collector, matching the Python+ // services. A collector reachable over the public internet would+ // need TLS, and that is a deployment decision rather than a+ // default.+ otlptracegrpc.WithInsecure(),+ )+ if err != nil {+ return func(context.Context) error { return nil }, err+ }++ res, err := resource.Merge(+ resource.Default(),+ resource.NewWithAttributes(+ semconv.SchemaURL,+ semconv.ServiceName(serviceName()),+ attribute.String("deployment.environment", environment()),+ ),+ )+ if err != nil {+ // A resource merge failure is a schema mismatch, not a reason to+ // run untraced. Fall back to the default resource.+ res = resource.Default()+ }++ provider := sdktrace.NewTracerProvider(+ sdktrace.WithBatcher(exporter),+ sdktrace.WithResource(res),+ sdktrace.WithSampler(sampler()),+ )+ otel.SetTracerProvider(provider)++ // W3C by default so a trace started by the API continues here. Without+ // this the ingest spans form their own disconnected trace, which looks+ // like instrumentation and is not.+ otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(+ propagation.TraceContext{},+ propagation.Baggage{},+ ))++ return func(shutdownCtx context.Context) error {+ flushCtx, cancel := context.WithTimeout(shutdownCtx, 5*time.Second)+ defer cancel()+ return provider.Shutdown(flushCtx)+ }, nil+}++// Tracer returns a named tracer. Safe before Setup: the global provider+// defaults to a no-op.+func Tracer(name string) trace.Tracer {+ return otel.Tracer(name)+}++func serviceName() string {+ if name := strings.TrimSpace(os.Getenv("OTEL_SERVICE_NAME")); name != "" {+ return name+ }+ return defaultServiceName+}++func environment() string {+ for _, key := range []string{"AISOC_ENV", "ENVIRONMENT"} {+ if value := strings.TrimSpace(os.Getenv(key)); value != "" {+ return value+ }+ }+ return "unknown"+}++// sampler honours OTEL_TRACES_SAMPLER_ARG as a ratio.+//+// Ingest is the highest-volume service in the platform, so head sampling+// is the difference between a usable trace store and one that costs more+// than the pipeline. Parent-based so a sampled API request stays sampled+// all the way through rather than being re-decided here — a trace sampled+// at one hop and dropped at the next is worse than not sampling at all.+func sampler() sdktrace.Sampler {+ ratio := 0.05+ if raw := strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER_ARG")); raw != "" {+ if parsed, err := parseRatio(raw); err == nil {+ ratio = parsed+ }+ }+ return sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio))+}++func parseRatio(raw string) (float64, error) {+ value, err := strconv.ParseFloat(raw, 64)+ if err != nil {+ return 0, err+ }+ if value < 0 {+ value = 0+ }+ if value > 1 {+ value = 1+ }+ return value, nil+}++// stripScheme normalises an endpoint for the gRPC exporter, which wants+// host:port rather than a URL. The Python services accept the URL form and+// the same env var is shared, so accepting both is the difference between+// one variable and two.+func stripScheme(endpoint string) string {+ for _, prefix := range []string{"http://", "https://", "grpc://"} {+ endpoint = strings.TrimPrefix(endpoint, prefix)+ }+ return strings.TrimSuffix(endpoint, "/")+}diff --git a/services/ingest/internal/telemetry/telemetry_test.go b/services/ingest/internal/telemetry/telemetry_test.gonew file mode 100644index 000000000..72a780469--- /dev/null+++ b/services/ingest/internal/telemetry/telemetry_test.go@@ -0,0 +1,96 @@+package telemetry++import (+ "context"+ "testing"+)++// Ingest is the pipeline's front door. Tracing that can refuse traffic, or+// that silently emits into nothing, is worse than no tracing — so these+// tests are about the disabled and misconfigured paths rather than the+// happy one.++func TestDisabledWhenNoEndpointConfigured(t *testing.T) {+ t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")++ shutdown, err := Setup(context.Background())+ if err != nil {+ t.Fatalf("no endpoint should not be an error: %v", err)+ }+ if shutdown == nil {+ t.Fatal("shutdown must be non-nil so the caller's defer is unconditional")+ }+ if err := shutdown(context.Background()); err != nil {+ t.Fatalf("shutting down a disabled tracer should be a no-op: %v", err)+ }+}++func TestTracerIsUsableBeforeSetup(t *testing.T) {+ // A span started before Setup must not panic. Ordering bugs in+ // startup are otherwise fatal rather than merely untraced.+ _, span := Tracer("test").Start(context.Background(), "pre-setup")+ span.End()+}++func TestStripScheme(t *testing.T) {+ // The Python services take a URL in the same variable and the gRPC+ // exporter wants host:port. Accepting both is the difference between+ // one env var and two.+ cases := map[string]string{+ "http://otel-collector:4317": "otel-collector:4317",+ "https://otel-collector:4317": "otel-collector:4317",+ "grpc://collector:4317": "collector:4317",+ "otel-collector:4317": "otel-collector:4317",+ "http://collector:4317/": "collector:4317",+ }+ for input, want := range cases {+ if got := stripScheme(input); got != want {+ t.Errorf("stripScheme(%q) = %q, want %q", input, got, want)+ }+ }+}++func TestParseRatioClamps(t *testing.T) {+ // A sampler arg outside [0,1] is a typo, not an instruction. Passing+ // it through would either disable sampling or panic the SDK.+ cases := map[string]float64{+ "0": 0,+ "0.25": 0.25,+ "1": 1,+ "-1": 0,+ "7": 1,+ }+ for input, want := range cases {+ got, err := parseRatio(input)+ if err != nil {+ t.Fatalf("parseRatio(%q): %v", input, err)+ }+ if got != want {+ t.Errorf("parseRatio(%q) = %v, want %v", input, got, want)+ }+ }+ if _, err := parseRatio("not-a-number"); err == nil {+ t.Error("a non-numeric sampler arg should error, not default silently")+ }+}++func TestSamplerFallsBackOnGarbage(t *testing.T) {+ // The fallback matters more than the parse: an unparseable value must+ // leave sampling at the default, not at zero. Zero looks identical to+ // "tracing is broken".+ t.Setenv("OTEL_TRACES_SAMPLER_ARG", "not-a-number")+ if sampler() == nil {+ t.Fatal("sampler must never be nil")+ }+}++func TestServiceNameIsOverridable(t *testing.T) {+ t.Setenv("OTEL_SERVICE_NAME", "")+ if got := serviceName(); got != defaultServiceName {+ t.Errorf("default service name = %q, want %q", got, defaultServiceName)+ }+ t.Setenv("OTEL_SERVICE_NAME", "aisoc-ingest-canary")+ if got := serviceName(); got != "aisoc-ingest-canary" {+ t.Errorf("override ignored: got %q", got)+ }+}diff --git a/services/ingest/main.go b/services/ingest/main.goindex 9331bade7..3d99204d0 100644--- a/services/ingest/main.go+++ b/services/ingest/main.go@@ -22,6 +22,7 @@ import ("github.com/beenuar/aisoc/services/ingest/internal/normalizer""github.com/beenuar/aisoc/services/ingest/internal/publisher""github.com/beenuar/aisoc/services/ingest/internal/server"+ "github.com/beenuar/aisoc/services/ingest/internal/telemetry""github.com/jackc/pgx/v5/pgxpool""github.com/rs/zerolog""github.com/rs/zerolog/log"@@ -42,6 +43,24 @@ func main() {log.Info().Str("service", "ingest").Msg("Starting AiSOC Ingest Service")+ // Tracing. `ingest` and `realtime` were the two uninstrumented ends of+ // the Kafka spine, so a trace started at the API stopped at the+ // pipeline boundary — exactly where the interesting latency is. No-ops+ // unless OTEL_EXPORTER_OTLP_ENDPOINT is set, because emitting spans+ // into a connection error is worse than emitting none.+ tracingCtx := context.Background()+ shutdownTracing, err := telemetry.Setup(tracingCtx)+ if err != nil {+ // Degraded, not fatal: ingest is the pipeline's front door and+ // must not refuse traffic because a collector is unreachable.+ log.Warn().Err(err).Msg("tracing disabled — exporter could not start")+ }+ defer func() {+ if err := shutdownTracing(tracingCtx); err != nil {+ log.Warn().Err(err).Msg("tracing shutdown incomplete; recent spans may be lost")+ }+ }()+cfg, err := config.Load()if err != nil {log.Fatal().Err(err).Msg("Failed to load configuration")diff --git a/services/realtime/package.json b/services/realtime/package.jsonindex ae7628ff0..162af8cd8 100644--- a/services/realtime/package.json+++ b/services/realtime/package.json@@ -28,5 +28,12 @@"@types/ws": "^8.5.10","tsx": "^4.23.15","typescript": "^5.3.3"+ },+ "optionalDependencies": {+ "@opentelemetry/api": "^1.9.0",+ "@opentelemetry/sdk-node": "^0.57.0",+ "@opentelemetry/sdk-trace-base": "^1.30.0",+ "@opentelemetry/resources": "^1.30.0",+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0"}}diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.tsindex 50def956c..a1c97b94a 100644--- a/services/realtime/src/index.ts+++ b/services/realtime/src/index.ts@@ -9,6 +9,7 @@ import rateLimit from 'express-rate-limit';import { PushManager } from './push';import { resolveTicketSecret, verifyRealtimeTicket } from './auth';+import { setupTelemetry, type Shutdown } from './telemetry';const log = pino({ level: process.env.LOG_LEVEL || 'info' });@@ -693,9 +694,17 @@ app.get('/healthz', reportHealth);// Node defaults to "::" when IPv6 is available, but be explicit to match the// other services and avoid surprises if a future Node release changes the// default or the container is launched with IPv6 disabled.+// Tracing. `ingest` and `realtime` were the two uninstrumented ends of the+// Kafka spine, so a trace started at the API stopped at the pipeline+// boundary — exactly where the interesting latency is. No-ops unless+// OTEL_EXPORTER_OTLP_ENDPOINT is set.+let shutdownTelemetry: Shutdown = async () => {};+server.listen(PORT, '::', async () => {log.info({ port: PORT, host: '::' }, 'AiSOC Real-time service started');+ shutdownTelemetry = await setupTelemetry(log);+// Start the two Kafka consumers concurrently. Each is wrapped in its own// try/catch so a failure on the graph topic (e.g. it doesn't exist yet on// a brand-new cluster) does NOT block the higher-priority fused-alerts@@ -721,3 +730,20 @@ server.listen(PORT, '::', async () => {}})();});++// Flush spans on the way out. Without this the exporter drops the spans+// from the final seconds before a restart, which are disproportionately+// the ones someone is looking for.+for (const signal of ['SIGTERM', 'SIGINT'] as const) {+ process.once(signal, () => {+ log.info({ signal }, 'shutting down');+ void shutdownTelemetry().finally(() => {+ server.close(() => process.exit(0));+ // Do not wait forever on lingering WebSocket connections: a+ // fan-out service always has open sockets, so close() alone may+ // never resolve and the container would be SIGKILLed with spans+ // still buffered.+ setTimeout(() => process.exit(0), 5000).unref();+ });+ });+}diff --git a/services/realtime/src/telemetry.ts b/services/realtime/src/telemetry.tsnew file mode 100644index 000000000..e977102d8--- /dev/null+++ b/services/realtime/src/telemetry.ts@@ -0,0 +1,130 @@+/**+ * OpenTelemetry tracing for the realtime service.+ *+ * `api`, `agents`, `ueba` and `honeytokens` were instrumented; `ingest`+ * (Go) and `realtime` (TypeScript) were not — and those two are the ends+ * of the Kafka spine. A trace therefore began at the API and stopped at+ * the pipeline boundary, which is where the interesting latency lives: an+ * alert that takes eight seconds to reach a browser is invisible if+ * nothing spans the part that took eight seconds.+ *+ * Three decisions worth stating, all of them about not making things+ * worse:+ *+ * **Off unless an endpoint is configured.** Defaulting it on sends every+ * span into a connection error on deployments with no collector, which+ * fills the logs and makes a missing trace ambiguous between "no span"+ * and "no collector".+ *+ * **Loaded dynamically.** The SDK is an optional dependency, so a+ * deployment that does not want it does not have to install it. A missing+ * package disables tracing with a log line rather than failing to boot —+ * realtime is a fan-out service and must not refuse connections because a+ * telemetry package is absent.+ *+ * **Never throws.** Every path returns a shutdown function, so the+ * caller's shutdown handler is unconditional and cannot be skipped on an+ * error path.+ */++import type pino from 'pino';++export type Shutdown = () => Promise<void>;++const NOOP: Shutdown = async () => {};++/** Strip a URL scheme; the OTLP gRPC exporter wants `host:port`.+ *+ * The Python services accept the URL form in the same environment+ * variable, so accepting both is the difference between one variable and+ * two. Exported for testing — it is the part most likely to be wrong and+ * least likely to be noticed, because a malformed endpoint fails at+ * export time rather than at startup.+ */+export function stripScheme(endpoint: string): string {+ return endpoint+ .replace(/^https?:\/\//, '')+ .replace(/^grpc:\/\//, '')+ .replace(/\/+$/, '');+}++/** Sampling ratio from `OTEL_TRACES_SAMPLER_ARG`, clamped to [0, 1].+ *+ * A value outside the range is a typo, not an instruction; passing it+ * through would either disable sampling entirely or be rejected by the+ * SDK at a point far from the mistake.+ */+export function samplingRatio(raw: string | undefined, fallback = 0.05): number {+ if (raw === undefined || raw.trim() === '') return fallback;+ const parsed = Number(raw);+ if (!Number.isFinite(parsed)) return fallback;+ return Math.min(1, Math.max(0, parsed));+}++export async function setupTelemetry(log: pino.Logger): Promise<Shutdown> {+ const endpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || '').trim();+ if (!endpoint) {+ // Not a warning. A deployment without a collector is supported, and+ // emitting spans nobody collects is worse than emitting none.+ log.debug('tracing disabled: OTEL_EXPORTER_OTLP_ENDPOINT is not set');+ return NOOP;+ }++ try {+ const [{ NodeSDK }, { OTLPTraceExporter }, { Resource }, api] =+ await Promise.all([+ import('@opentelemetry/sdk-node'),+ import('@opentelemetry/exporter-trace-otlp-grpc'),+ import('@opentelemetry/resources'),+ import('@opentelemetry/api'),+ ]);+ const { TraceIdRatioBasedSampler, ParentBasedSampler } = await import(+ '@opentelemetry/sdk-trace-base'+ );++ const sdk = new NodeSDK({+ // `Resource` rather than the 2.x `resourceFromAttributes`: the+ // pinned SDK line is 1.30, and reaching for the newer helper+ // type-checks only against a version this service does not install.+ resource: new Resource({+ 'service.name': process.env.OTEL_SERVICE_NAME || 'aisoc-realtime',+ 'deployment.environment':+ process.env.AISOC_ENV || process.env.ENVIRONMENT || 'unknown',+ }),+ traceExporter: new OTLPTraceExporter({ url: `http://${stripScheme(endpoint)}` }),+ // Parent-based so a sampled request stays sampled through this hop+ // rather than being re-decided. A trace sampled at one service and+ // dropped at the next is worse than not sampling at all: it looks+ // like the second service did not participate.+ sampler: new ParentBasedSampler({+ root: new TraceIdRatioBasedSampler(+ samplingRatio(process.env.OTEL_TRACES_SAMPLER_ARG),+ ),+ }),+ });++ sdk.start();+ log.info({ endpoint }, 'tracing enabled');++ return async () => {+ try {+ // Flush before exit. An unflushed exporter drops the spans from+ // the final seconds before a restart, and those are+ // disproportionately the ones someone is looking for.+ await sdk.shutdown();+ } catch (err) {+ log.warn({ err }, 'tracing shutdown incomplete; recent spans may be lost');+ }+ void api;+ };+ } catch (err) {+ // A missing optional dependency, or an SDK that would not start.+ // Realtime is a fan-out service and must not refuse connections+ // because telemetry is unavailable.+ log.warn(+ { err },+ 'tracing disabled: the OpenTelemetry SDK could not be loaded or started',+ );+ return NOOP;+ }+}