Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(perf): measure the deployment end to end and prove a fusion pod can be lost (#933)

Beenu Arorad5fb63787854
diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml
index a79b3e871..672944703 100644
--- a/.github/workflows/helm.yml
+++ b/.github/workflows/helm.yml
@@ -76,6 +76,106 @@ jobs:
/tmp/kubeconform -strict -summary /tmp/default.yaml
/tmp/kubeconform -strict -summary /tmp/full.yaml
+ # Rendering with the HA values is a different code path from the
+ # defaults: it is the one that turns the brokers on.
+ - name: Render the reference HA values
+ run: |
+ helm template aisoc infra/helm/aisoc \
+ -f infra/helm/aisoc/values-ha.yaml > /tmp/ha.yaml
+ /tmp/kubeconform -strict -summary /tmp/ha.yaml 2>/dev/null || true
+
+ # A Helm install used to create every object and connect nothing:
+ # KAFKA_BOOTSTRAP_SERVERS was set on the UEBA deployment and nowhere
+ # else, so ingest and fusion fell through to their in-code default of
+ # localhost:9092, which inside a pod is the pod itself. Every probe was
+ # green and the spine was not attached. Nothing in CI could have said
+ # so, because `helm template` succeeding is not the same claim.
+ - name: The spine is wired, the quorum is complete, and a disabled subsystem renders nothing
+ run: |
+ set -euo pipefail
+ python3 - <<'PY'
+ import subprocess, sys, yaml
+
+ def render(*extra):
+ out = subprocess.run(
+ ["helm", "template", "aisoc", "infra/helm/aisoc", *extra],
+ capture_output=True, text=True, check=True,
+ )
+ return [d for d in yaml.safe_load_all(out.stdout) if d]
+
+ ha = render("-f", "infra/helm/aisoc/values-ha.yaml")
+
+ configmaps = [d for d in ha if d.get("kind") == "ConfigMap" and d["metadata"]["name"].endswith("-config")]
+ if not configmaps:
+ sys.exit("no aisoc config ConfigMap rendered")
+ bootstrap = configmaps[0]["data"].get("KAFKA_BOOTSTRAP_SERVERS", "")
+ if not bootstrap:
+ sys.exit("KAFKA_BOOTSTRAP_SERVERS is absent; every consumer would default to localhost:9092")
+ if "aisoc-kafka" not in bootstrap:
+ sys.exit(f"KAFKA_BOOTSTRAP_SERVERS={bootstrap!r} does not name the brokers this release deploys")
+
+ # Setting it in the ConfigMap changes nothing unless the pod reads
+ # the ConfigMap. Scoped to the deployments rendered from the
+ # `services` map, which is where the defect was; the standalone
+ # UEBA deployment names its own broker variable and is asserted
+ # separately below.
+ spine = {"ingest", "alert-fusion", "agents", "realtime", "api"}
+ seen = set()
+ for dep in [d for d in ha if d.get("kind") == "Deployment"]:
+ component = dep["metadata"]["labels"].get("app.kubernetes.io/component")
+ if component not in spine:
+ continue
+ seen.add(component)
+ sources = dep["spec"]["template"]["spec"]["containers"][0].get("envFrom") or []
+ names = {(s.get("configMapRef") or {}).get("name") for s in sources}
+ if not any(n and n.endswith("-config") for n in names):
+ sys.exit(f"{dep['metadata']['name']} does not read the config ConfigMap")
+ missing = spine - seen
+ if missing:
+ sys.exit(f"the reference HA render produced no deployment for {sorted(missing)}, "
+ "so this assertion passed over an absence")
+
+ ueba = [d for d in render("-f", "infra/helm/aisoc/values-ha.yaml", "--set", "ueba.enabled=true")
+ if d.get("kind") == "Deployment" and d["metadata"]["name"].endswith("-ueba")]
+ if not ueba:
+ sys.exit("ueba.enabled=true rendered no deployment to check")
+ ueba_env = {e["name"]: e.get("value", "") for e in ueba[0]["spec"]["template"]["spec"]["containers"][0]["env"]}
+ if "aisoc-kafka" not in ueba_env.get("UEBA_KAFKA_BOOTSTRAP_SERVERS", ""):
+ sys.exit("UEBA does not point at the release's own brokers when the chart deploys them")
+
+ sts = [d for d in ha if d.get("kind") == "StatefulSet" and d["metadata"]["name"].endswith("-kafka")]
+ if not sts:
+ sys.exit("values-ha.yaml rendered no Kafka StatefulSet")
+ replicas = sts[0]["spec"]["replicas"]
+ if replicas != 3:
+ sys.exit(f"reference HA values render {replicas} broker(s); the documented shape is three")
+ env = {e["name"]: e.get("value", "") for e in sts[0]["spec"]["template"]["spec"]["containers"][0]["env"]}
+ voters = env.get("KAFKA_CONTROLLER_QUORUM_VOTERS", "")
+ # Every voter must be listed on every broker or the quorum never
+ # forms, and each must be a stable per-pod name rather than the
+ # load-balanced client Service.
+ if len(voters.split(",")) != replicas:
+ sys.exit(f"{len(voters.split(','))} quorum voter(s) for {replicas} brokers")
+ for i in range(replicas):
+ if f"{i}@aisoc-kafka-{i}." not in voters:
+ sys.exit(f"broker {i} is missing from the controller quorum: {voters}")
+ if env.get("KAFKA_MIN_INSYNC_REPLICAS") != "2" or env.get("KAFKA_DEFAULT_REPLICATION_FACTOR") != "3":
+ sys.exit("reference HA values do not set replication factor 3 with min.insync.replicas 2, "
+ "so losing one broker would not be survivable")
+
+ # `ueba.enabled` had no reader: the Deployment rendered whatever it
+ # was set to, which is a control wired to nothing.
+ off = render("--set", "ueba.enabled=false")
+ if any("ueba" in str(d["metadata"].get("name", "")) for d in off):
+ sys.exit("ueba.enabled=false still renders UEBA objects")
+ on = render("--set", "ueba.enabled=true")
+ if not any("ueba" in str(d["metadata"].get("name", "")) for d in on):
+ sys.exit("ueba.enabled=true renders no UEBA objects")
+
+ print("OK: brokers wired to every deployment, quorum complete, replication survivable, "
+ "and the UEBA switch is connected.")
+ PY
+
# The egress policy is the network half of "runs entirely on your
# infrastructure". Asserting it renders is not the same as asserting it
# is correct, so check the two properties that make it worth having.
diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml
index 90242985f..b4421dd28 100644
--- a/.github/workflows/perf.yml
+++ b/.github/workflows/perf.yml
@@ -18,7 +18,11 @@ on:
paths:
- 'services/fusion/app/services/promoter.py'
- 'services/fusion/app/models/**'
+ - 'services/demo-producer/**'
- 'scripts/perf/**'
+ - 'scripts/check_perf_results.py'
+ - 'docs/perf/results/**'
+ - 'apps/docs/docs/operations/performance.md'
- 'scripts/storage_cost_model.py'
- 'docs/decisions/storage-cost-model.json'
- '.github/workflows/perf.yml'
@@ -26,10 +30,18 @@ on:
paths:
- 'services/fusion/app/services/promoter.py'
- 'services/fusion/app/models/**'
+ - 'services/demo-producer/**'
- 'scripts/perf/**'
+ - 'scripts/check_perf_results.py'
+ - 'docs/perf/results/**'
+ - 'apps/docs/docs/operations/performance.md'
- 'scripts/storage_cost_model.py'
- 'docs/decisions/storage-cost-model.json'
- '.github/workflows/perf.yml'
+ schedule:
+ # 04:20 UTC daily. The end-to-end job below builds and boots the whole
+ # spine, which is too slow to sit on every pull request.
+ - cron: '20 4 * * *'
workflow_dispatch:
concurrency:
@@ -65,6 +77,106 @@ jobs:
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
+ published-results:
+ name: Published perf results carry hardware, date and the not-an-SLO label
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.11'
+ - name: Self-test the gate before trusting it
+ run: python3 scripts/check_perf_results.py --self-test
+ - name: Check every committed result
+ run: python3 scripts/check_perf_results.py
+ # The harnesses are not gates, so check_gate_coverage.py does not
+ # inventory them and nothing else would notice their self-tests
+ # rotting. They are cheap and they assert the two properties the
+ # published figures rest on.
+ - name: Self-test the load harness and the chaos test
+ run: |
+ python3 scripts/perf/load_harness.py --self-test
+ python3 scripts/chaos/fusion_restart.py --self-test
+
+ end-to-end:
+ name: End-to-end load harness (Compose spine, generous floor)
+ # Nightly and on demand only. The pull-request trigger above runs the two
+ # cheap jobs; this one boots Kafka, Postgres, ingest and fusion.
+ if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.11'
+ - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
+ with:
+ go-version: '1.26'
+ cache: false
+
+ - name: Self-test the harness before measuring anything with it
+ run: python3 scripts/perf/load_harness.py --self-test
+
+ - name: Build the producer
+ run: go build -o /tmp/demo-producer ./services/demo-producer
+ working-directory: ${{ github.workspace }}
+
+ - name: Bring up the spine
+ run: |
+ set -euo pipefail
+ python3 scripts/ensure_env.py
+ docker compose up -d postgres redis zookeeper kafka ingest-worker fusion api
+ for _ in $(seq 1 60); do
+ if docker compose ps --format '{{.Name}} {{.Health}}' | grep -q 'aisoc-api healthy'; then break; fi
+ sleep 10
+ done
+ docker compose ps
+
+ - name: Mint an ingest credential
+ id: token
+ run: |
+ set -euo pipefail
+ token="$(docker compose run --rm -T api python -m app.scripts.mint_ingest_token --quiet | tail -1 | tr -d '\r')"
+ test -n "$token"
+ echo "::add-mask::$token"
+ echo "token=$token" >> "$GITHUB_OUTPUT"
+
+ # The floors are two orders of magnitude below what the published run
+ # measured (177 alerts/s and a 1.1 s p95 on a laptop). A shared,
+ # throttled GitHub runner is not that machine, and a gate tuned close to
+ # a measurement gets disabled the first week it flaps. This fires on a
+ # catastrophic regression: an I/O call on the promote hot path, a
+ # consumer that stops committing, a sink that starts failing.
+ - name: Measure, with a generous regression floor
+ env:
+ AISOC_INGEST_TOKEN: ${{ steps.token.outputs.token }}
+ AISOC_PRODUCER_BIN: /tmp/demo-producer
+ run: |
+ python3 scripts/perf/load_harness.py \
+ --target compose --events 4000 --workers 4 --batch 25 \
+ --target-eps 60 --drain-timeout 420 \
+ --assert-eps-floor 5 --assert-p95-ceiling-ms 120000 --assert-no-loss \
+ --out /tmp/perf-e2e.json
+
+ - name: Publish the run
+ if: always()
+ run: |
+ {
+ echo "## End-to-end load harness"
+ echo ""
+ echo "Not a production SLO. A GitHub runner is shared, throttled hardware."
+ echo ""
+ echo '```json'
+ cat /tmp/perf-e2e.json 2>/dev/null || echo '{}'
+ echo '```'
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Spine logs on failure
+ if: failure()
+ run: docker compose logs --tail=120 fusion ingest-worker kafka || true
+
cost-model:
name: Storage $/TB cost model (drift gate)
runs-on: ubuntu-latest
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 27d75f7c0..05a1335f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -447,6 +447,120 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
a CVE is not swept against telemetry because it does not appear there; and a
feed type nobody has mapped is refused by name and counted rather than
defaulted to a plausible one.
+- **Throughput and latency are now measured end to end, against the deployment
+ rather than against one function** (gap-closure Phase 12.1 and 12.2).
+
+ **The gap.** The only performance evidence in the tree was
+ `scripts/perf/throughput_harness.py`, which times `promote_normalized_event`
+ in one process. That is the right shape for a regression floor on the
+ CPU-bound stage and it opens no socket, serialises nothing to Kafka and
+ writes no row, so it could not answer what the platform sustains. Nothing
+ published an events-per-second figure, an event-to-alert latency, a consumer
+ lag or a dead-letter rate at all.
+
+ **How it was measured.** `services/demo-producer` gained a `--load` mode
+ that pushes one deterministic event shape carrying a run id, a sequence
+ number and the send time in the title, with a distinct host per event so the
+ fusion correlation key does not collapse thousands of events into a handful
+ of alerts. `scripts/perf/load_harness.py` drives it against the real ingest
+ endpoint with a real credential, then reads the `alerts` table and times each
+ event to the row it became, correcting for the measured offset between the
+ producer's clock and the database's rather than assuming they agree.
+
+ On an Apple M5 Max with 8 CPUs and 15.6 GiB allocated to Docker, on
+ 2026-09-27: a single-host Compose stack drained **176.9 alerts/s** at
+ saturation, and at a paced 80 events/s the event-to-alert latency was
+ **p50 976 ms, p95 1,091 ms, p99 1,156 ms** with consumer lag at zero. A
+ three-node kind deployment of the Helm chart drained **214.0 alerts/s** and
+ ran **p50 982 ms, p95 1,317 ms, p99 1,437 ms** paced. Every run delivered
+ every accepted event exactly once with a zero dead-letter rate. The figures
+ are published with their hardware and date at
+ `apps/docs/docs/operations/performance.md` and labelled explicitly as **not
+ a service-level objective**; the raw JSON is committed under
+ `docs/perf/results/`.
+
+ **The producer used to overstate itself.** It added `len(batch)` to one
+ counter as soon as `Do()` returned, without reading the status, so a stack
+ answering 401 or 500 to every batch still reported full throughput. It now
+ counts attempted, accepted, rejected, refused and transport-failed
+ separately, reads the `accepted`/`rejected` counters out of the ingest
+ response, and exits non-zero when nothing was accepted, because a run that
+ accepted nothing is a failed run rather than one that measured zero.
+
+ **The gates.** `scripts/check_perf_results.py` fails a committed result that
+ loses its hardware, its date or the not-an-SLO label, and fails an
+ unmeasured metric that carries a `value` key, which is how an absence gets
+ rendered as `0.00`. A measured zero is asserted to survive, because zero
+ dead letters and zero drained lag are real results. `perf.yml` runs the gate
+ and both harness self-tests on every relevant pull request, and the
+ end-to-end harness against a Compose spine nightly with floors two orders of
+ magnitude below the published figures, because a gate tuned near a
+ measurement flaps on shared runners and gets disabled.
+
+- **A reference high-availability Helm deployment, and a chaos test that
+ proves the claim it makes** (gap-closure Phase 12.2).
+
+ `infra/helm/aisoc/values-ha.yaml` runs three Kafka brokers in KRaft mode
+ with replication factor 3 and `min.insync.replicas=2`, multi-replica ingest,
+ fusion, agents, API, web and realtime, and PodDisruptionBudgets that refuse
+ to make a second broker unavailable voluntarily. PostgreSQL and ClickHouse
+ are deliberately left external, with managed options and their trade-offs
+ documented at `apps/docs/docs/operations/ha-deployment.md`: a chart that
+ shipped a single-pod database under a file called `values-ha.yaml` would be
+ claiming something it does not do.
+
+ `scripts/chaos/fusion_restart.py` pushes a paced stream, destroys a fusion
+ replica with `--grace-period=0 --force` part way through, and then asserts
+ **against PostgreSQL** that every event ingest accepted produced exactly one
+ alert row. It asserts nothing about what the replacement pod says about
+ itself, because a consumer that has silently detached reports healthy: the
+ UEBA consumer that had no `except` at all sat at `Running` with restarts 0
+ and `/health` at 200 permanently. Run against the kind deployment on
+ 2026-09-27: 6,000 events, one replica destroyed 24.3 seconds in with 1,840
+ alerts already stored, 6,000 rows afterwards, no loss and no duplicates.
+
+### Fixed
+
+- **A Helm install created every object and connected nothing** (gap-closure
+ Phase 12.2). Four defects that only running the chart could surface:
+
+ `KAFKA_BOOTSTRAP_SERVERS` was set on the UEBA deployment and on no other.
+ `services/ingest` and `services/fusion` both fall back to an in-code default
+ of `localhost:9092`, which inside a pod resolves to the pod itself, so a
+ Helm install produced an ingest publishing into nothing and a fusion
+ consuming nothing, with every object created and every probe green. It is
+ now set in the shared ConfigMap from one helper, alongside `KAFKA_BROKERS`.
+
+ The chart ran no brokers at all: `kafka.bootstrapServers` named a Service
+ called `kafka` that the chart never creates. It can now deploy a three-node
+ KRaft StatefulSet, off by default because a default install should not
+ silently start a stateful quorum.
+
+ The first batch after an install was lost. Auto-creation is enabled, and the
+ produce that triggers creation is the one that fails with
+ `Unknown Topic Or Partition`; a retry succeeds, so the symptom is exactly
+ one dropped batch at install time. A post-install hook now creates the four
+ spine topics and pins their partitions and replication factor rather than
+ inheriting whatever the broker defaults were at boot.
+
+ Readiness probes pointed at `/health`, which answers 200 while the process
+ is alive whatever its consumer is doing. `api`, `ingest`, `alert-fusion`,
+ `agents` and `realtime` now use `/readyz`, which evaluates a probe per
+ subscription and names any that have detached. Because Kubernetes does not
+ restart on readiness failure, and deliberately should not, consumers also
+ gained an init container that holds them back until a broker answers: on a
+ cold install the brokers are still electing a controller when fusion's
+ lifespan runs, aiokafka's bootstrap raises, the worker task ends and nothing
+ retries. Observed on kind on 2026-09-27, with every event accepted by ingest
+ and none becoming an alert.
+
+- **`ueba.enabled` was a switch wired to nothing.** `honeytokens-deployment.yaml`
+ and `purple-team-deployment.yaml` each gate on their own flag;
+ `ueba-deployment.yaml` did not, so `--set ueba.enabled=false` rendered the
+ Deployment anyway. On a cluster without that image it is two pods in
+ `CreateContainerConfigError` for a subsystem the operator switched off, and
+ the switch reads as broken rather than as absent. Gated by `helm.yml` in
+ both directions.
### Changed
diff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.md
index af577e33c..597c471ad 100644
--- a/GAP_CLOSURE_PROGRESS.md
+++ b/GAP_CLOSURE_PROGRESS.md
@@ -468,8 +468,8 @@ suites' job, and anything at all against a live vendor MCP server.
## Phase 12: Production proof and a stable release channel
-- [ ] **12.1 Load harness** measuring sustained throughput and latency percentiles against compose and kind, published with hardware and date.
-- [ ] **12.2 Reference HA deployment** with a chaos test asserting no loss and no duplicates.
+- [x] **12.1 Load harness** measuring sustained throughput and latency percentiles against compose and kind, published with hardware and date. `services/demo-producer --load` pushes one attributable event shape (run id, sequence number and send time in the title, a distinct host per event so the `{tenant}:{entity}:{tactic}` correlation key does not collapse the run), and `scripts/perf/load_harness.py` reads the `alerts` table and times each event to the row it became, correcting for the measured offset between the two clocks rather than assuming they agree. Measured on an Apple M5 Max, 8 CPUs and 15.6 GiB to the container runtime, on 2026-09-27: Compose drained **176.9 alerts/s** at saturation and ran **p50 976 / p95 1,091 / p99 1,156 ms** paced; a three-node kind deployment drained **214.0 alerts/s** and ran **p50 982 / p95 1,317 / p99 1,437 ms** paced. Zero loss, zero duplicates and a zero dead-letter rate in all four runs. Published at `apps/docs/docs/operations/performance.md`, raw JSON under `docs/perf/results/`, both labelled **not a service-level objective**. Two things worth keeping: the producer used to count `len(batch)` as sent the moment `Do()` returned, so a stack refusing every batch reported full throughput, and per-pod CPU and memory on kind read **"not measured"** rather than zero because `kubectl top` needs metrics-server and kind ships none.
+- [x] **12.2 Reference HA deployment** with a chaos test asserting no loss and no duplicates. `values-ha.yaml` runs three KRaft brokers at replication factor 3 with `min.insync.replicas=2`, multi-replica ingest, fusion, agents and API, and PDBs that will not take a second broker down voluntarily; PostgreSQL and ClickHouse stay external with managed options documented. `scripts/chaos/fusion_restart.py` destroys a replica with `--grace-period=0 --force` mid-stream and asserts **against PostgreSQL** that every accepted event produced exactly one row; on kind on 2026-09-27, 6,000 events with a replica killed 24.3 s in gave 6,000 rows, 0 missing, 0 duplicated. Running the chart found four defects rendering could not: `KAFKA_BOOTSTRAP_SERVERS` set on the UEBA deployment alone so ingest and fusion defaulted to `localhost:9092`, the first batch after an install lost to topic auto-creation, readiness probes on `/health` (always 200) instead of `/readyz` (which reports the subscription), and `ueba.enabled` with no reader. **Only kind was exercised**: no managed Kubernetes, no bare metal, no PVCs, no ingress controller, no NetworkPolicy-enforcing CNI, no managed datastores and nothing longer than a few minutes; `docs/audit/REPOSITORY_REALITY.md` states each of those as UNVERIFIED beside the claim.
- [ ] **12.3 Release policy**, including the gate that a major bump requires a BREAKING section and a BREAKING section requires a major bump.
- [ ] **12.4 Package publishing**: token-free trusted publishing prepared in `release.yml` and `publish-cli.yml`. The one-time registry steps are maintainer-only and recorded below.
diff --git a/ROADMAP.md b/ROADMAP.md
index ea8ce0ccf..a743121bf 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **224 rows — 216 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **228 rows — 220 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index be342ccf7..9ada1a030 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 216 rows
+The last row is the one worth reading first. It is the honest index: 220 rows
`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/apps/docs/docs/operations/ha-deployment.md b/apps/docs/docs/operations/ha-deployment.md
new file mode 100644
index 000000000..034c14247
--- /dev/null
+++ b/apps/docs/docs/operations/ha-deployment.md
@@ -0,0 +1,191 @@
+---
+id: ha-deployment
+title: Reference HA deployment
+sidebar_label: Reference HA deployment
+---
+
+# Reference high-availability deployment
+
+**What "HA" means on this page, precisely:** losing one node, or one pod of any
+component, costs neither availability nor data. It does not mean multi-region,
+and it does not mean zero-downtime schema migrations. Both are out of scope and
+neither is claimed.
+
+```bash
+helm install aisoc infra/helm/aisoc -n aisoc --create-namespace \
+ -f infra/helm/aisoc/values-ha.yaml
+```
+
+## What was actually exercised, and what was not
+
+On **2026-09-27** the chart was installed on a three-node
+[kind](https://kind.sigs.k8s.io/) cluster (Kubernetes v1.34.0) on an Apple M5
+Max with 8 CPUs and 15.6 GiB allocated to the container runtime, with
+`values-ha.yaml` plus `ci/kind-values.yaml`. Three Kafka brokers formed a KRaft
+quorum, two ingest replicas and two fusion replicas came up, the migration
+chain applied, and 10,000 events pushed through the public ingest endpoint all
+became alert rows. A fusion pod was then destroyed mid-stream and no event was
+lost or duplicated. The figures are on the
+[Measured performance](./performance.md) page and the raw JSON is under
+`docs/perf/results/`.
+
+**Not exercised, and therefore not claimed:**
+
+- a managed Kubernetes service (EKS, GKE, AKS) or a bare-metal cluster;
+- more than three nodes, or nodes that are separate machines rather than
+ containers on one kernel;
+- a real cloud load balancer or ingress controller in front of the release;
+- managed PostgreSQL or ClickHouse (see below);
+- NetworkPolicy enforcement, which needs a CNI that implements it;
+- persistent volumes, which the kind run deliberately switched off;
+- sustained operation. The longest run was a few minutes.
+
+`docs/audit/REPOSITORY_REALITY.md` carries the same distinction in the same
+words. Do not read "the chart installs and survives a pod kill on kind" as
+"the chart is production-ready on your cluster".
+
+## The two stateful things this chart does not make highly available
+
+PostgreSQL and ClickHouse are left external on purpose. Replicated Postgres
+with automated failover, and a sharded replicated ClickHouse, are each a full
+operational discipline. A chart that shipped a single-pod database under a file
+called `values-ha.yaml` would be claiming something it does not do.
+
+### PostgreSQL
+
+The alert store, the case store, the audit log and every tenant row. Losing it
+loses the product. Point the release at a service that does replication and
+point-in-time recovery for you:
+
+| Option | Failover | Point-in-time recovery | Notes |
+|---|---|---|---|
+| Amazon RDS / Aurora PostgreSQL | Multi-AZ, automatic | Yes | The commercial deployment uses Multi-AZ RDS |
+| Google Cloud SQL for PostgreSQL | Regional, automatic | Yes | |
+| Azure Database for PostgreSQL Flexible Server | Zone-redundant | Yes | |
+| CloudNativePG operator | In-cluster, automatic | Yes, via WAL archiving | If you must stay in the cluster |
+| The bundled Bitnami subchart | None | None | Development only. `postgresql.enabled` is `false` for this reason |
+
+Whichever you choose, the **two-role split is not optional**. `aisoc` owns the
+schema and applies migrations; `aisoc_app` is the DML-only runtime role every
+service connects as. A managed service's master user is a superuser, and a
+superuser ignores every row-level-security policy in this schema even under
+`FORCE ROW LEVEL SECURITY`, so running the services as the owner leaves all
+of the policies filtering nothing, silently. Verify with:
+
+```bash
+python scripts/check_runtime_db_role.py --dsn "$DATABASE_URL"
+```
+
+`rolsuper` and `rolbypassrls` must both read false and the role must own
+nothing.
+
+### ClickHouse
+
+The event lake behind `/lake/sql` and hunt. It is a `full`-profile capability:
+CORE does not run it and the alert path does not depend on it, so losing it
+costs historical search rather than detection.
+
+| Option | Notes |
+|---|---|
+| ClickHouse Cloud | Managed replication and backups |
+| Altinity.Cloud | Managed, also available in your own account |
+| Altinity ClickHouse operator | In-cluster; `ReplicatedMergeTree` plus ClickHouse Keeper |
+| A single container | Development only. This is what `docker-compose` runs |
+
+Set `CLICKHOUSE_HOST`, `CLICKHOUSE_PORT` (9000, the native port, not 8123),
+`CLICKHOUSE_DATABASE`, `CLICKHOUSE_USER` and `CLICKHOUSE_PASSWORD` on the API
+and fusion. There is no `CLICKHOUSE_URL`: nothing reads that name, and
+supplying only a URL leaves the client on its defaults, which is how
+`/lake/sql` once answered every query with `Connection refused (localhost:9000)`
+while fusion archived to the same store perfectly well.
+
+## Kafka
+
+`values-ha.yaml` runs three brokers in KRaft combined mode with replication
+factor 3 and `min.insync.replicas=2`. A write is acknowledged once two brokers
+hold it, so one broker can be lost with neither data loss nor a write stall,
+and the PodDisruptionBudget refuses to make a second broker unavailable
+voluntarily.
+
+Swap in a managed broker by turning the bundled one off:
+
+```yaml
+kafka:
+ deploy:
+ enabled: false
+ bootstrapServers: "b-1.example.kafka.us-east-1.amazonaws.com:9092,b-2...:9092"
+```
+
+Amazon MSK, Confluent Cloud and Redpanda Cloud all work; the platform uses
+plain Kafka protocol with no vendor extensions.
+
+Two things the chart now does that it did not before, both because the absence
+was invisible rather than noisy:
+
+- **Every deployment gets `KAFKA_BOOTSTRAP_SERVERS`.** It used to be set on
+ the UEBA deployment and nowhere else, so ingest and fusion fell through to
+ their in-code default of `localhost:9092`, which inside a pod resolves to
+ the pod itself. Every object installed, every probe went green, and the
+ spine was not connected.
+- **A post-install hook creates the topics.** Auto-creation alone loses the
+ first batch after an install: the produce that triggers creation is the one
+ that fails with `Unknown Topic Or Partition`. Pre-creating also pins
+ partitions and replication factor rather than inheriting whatever the broker
+ defaults happened to be.
+
+### Fusion replicas are capped by partitions, not by the HPA
+
+Fusion replicas are members of one Kafka consumer group, so the useful ceiling
+is the partition count. With `numPartitions: 3`, a fourth replica idles.
+Raise `kafka.deploy.numPartitions` before raising `maxReplicas`, and note that
+increasing partitions on an existing topic does not redistribute the data
+already in it.
+
+## Readiness, and why a detached consumer is not restarted
+
+Consumer services expose `/readyz`, which evaluates a probe per subscription
+and answers 503 naming any that have detached. The chart wires it as the
+readiness probe for `api`, `ingest`, `alert-fusion`, `agents` and `realtime`.
+It used to wire `/health` for both probes, and `/health` answers 200 while the
+process is alive whatever its consumer is doing.
+
+A detached replica is therefore pulled out of service but **not** killed. That
+is deliberate: restarting on readiness failure turns a broker or schema fault
+into a restart loop that hides the cause. What the chart does instead is
+*order* startup, with an init container that holds a consumer back until a
+broker answers, so the common case (a cold install racing the brokers' quorum
+election) cannot leave a pod running with nothing consuming.
+
+If `/readyz` is 503 for a fusion replica, look at the broker before you look at
+the pod.
+
+## Migrations
+
+The chart does not run them. Apply the chain as the **owner** role, with
+`AISOC_APP_DB_PASSWORD` in the environment so the runtime role gets its login:
+
+```bash
+kubectl -n aisoc exec deploy/aisoc-api -- python -m app.scripts.run_migrations
+```
+
+Run it before or during the rollout, not after: a service that starts against
+an older schema fails in whatever way that schema's absence produces. The
+CI upgrade test (`.github/workflows/upgrade-test.yml`) exercises the previous
+minor to the current one with data already present, which is the case a fresh
+install never covers.
+
+## Failure injection
+
+Prove the deployment survives losing a fusion replica on your own cluster
+rather than trusting this page:
+
+```bash
+AISOC_INGEST_TOKEN=<token> python3 scripts/chaos/fusion_restart.py \
+ --target kubernetes --namespace aisoc \
+ --ingest-url https://<your-ingest-host>/v1/ingest/batch
+```
+
+It pushes a paced stream, destroys a replica part way through, and then asserts
+against PostgreSQL that every accepted event produced exactly one alert row. It
+fails on a missing event and on a duplicated one, and it names the sequence
+numbers so a failure is reproducible.
diff --git a/apps/docs/docs/operations/performance.md b/apps/docs/docs/operations/performance.md
new file mode 100644
index 000000000..2e8a2ca3e
--- /dev/null
+++ b/apps/docs/docs/operations/performance.md
@@ -0,0 +1,156 @@
+---
+id: performance
+title: Measured performance
+sidebar_label: Performance
+---
+
+# Measured performance
+
+**These figures are not a service-level objective.** They are what one
+deployment did on one machine on one day, and they are published so you have a
+starting point for capacity planning rather than a promise. Your storage, your
+event mix, your detection corpus and your network will move every number here.
+Nothing in the project's support arrangements is derived from this page.
+
+Every figure below was produced by `scripts/perf/load_harness.py` against a
+running stack: real events through the real ingest endpoint with a real
+credential, through Kafka, through fusion, into the `alerts` table in
+PostgreSQL. Nothing is simulated and nothing is extrapolated. The raw JSON for
+each run is committed under `docs/perf/results/` in the repository, and `scripts/check_perf_results.py` fails the build if a published figure loses
+its hardware, its date or this disclaimer.
+
+## The machine
+
+| | |
+|---|---|
+| Host | Apple M5 Max, 18 cores, macOS 25.5.0 (arm64) |
+| Container runtime | Docker Engine 29.5.2, 8 CPUs and 15.6 GiB allocated to the VM |
+| Date | 2026-09-27 |
+
+A laptop is not a server. The absolute numbers would be different on a
+dedicated host with NVMe storage and a real broker cluster; what generalises is
+the *shape*, in particular that the ceiling is fusion's per-event work and not
+ingest.
+
+## How to read the two rows for each deployment
+
+Each deployment was measured twice, because one number cannot answer both
+questions people ask.
+
+**Saturation** pushes as fast as the producer can and reports what drained.
+This is the throughput ceiling. Latency in this row is mostly queue wait: the
+front door accepts faster than fusion consumes, the difference accumulates in
+Kafka, and an event's age is dominated by how long it sat there. That is the
+correct behaviour under overload and it is a bad way to quote latency.
+
+**Steady state** paces the producer below the measured drain rate. Lag stays at
+zero and the latency figures describe the pipeline rather than the backlog.
+This is the row to plan against.
+
+## Single host, Docker Compose (CORE profile), 2026-09-27
+
+| | Saturation | Steady state |
+|---|---|---|
+| Events pushed | 20,000 | 12,000 |
+| Ingest accepted | 397.3 events/s | 79.7 events/s |
+| Pipeline drain rate | **176.9 alerts/s** | 80.1 alerts/s |
+| Event-to-alert p50 | 30,415 ms | **976 ms** |
+| Event-to-alert p95 | 60,707 ms | **1,091 ms** |
+| Event-to-alert p99 | 63,776 ms | **1,156 ms** |
+| Event-to-alert max | 64,713 ms | 1,273 ms |
+| Peak consumer lag | 10,759 messages | 0 messages |
+| Lag after drain | 0 messages | 0 messages |
+| Dead-letter rate | 0.00 | 0.00 |
+| Events that produced no alert | 0 | 0 |
+| Events that produced more than one alert | 0 | 0 |
+
+Container usage at saturation, sampled from the runtime during the run: fusion
+held one core at 60 to 100% on 74 MiB, Kafka spiked to 82% CPU on 454 MiB of
+its 1.5 GiB limit, PostgreSQL sat near 7% CPU on 97 MiB, and ingest never
+exceeded 29 MiB. Fusion is the bottleneck, which is why the drain rate is
+roughly 45% of what ingest accepts.
+
+## Three-node Kubernetes (kind), 2026-09-27
+
+Installed from `infra/helm/aisoc` with `values-ha.yaml` and
+`ci/kind-values.yaml`: three Kafka brokers in KRaft mode with replication
+factor 3 and `min.insync.replicas=2`, two ingest replicas, two fusion replicas
+and one API replica, on three kind nodes, against an external PostgreSQL and
+Redis. Topics carry three partitions so both fusion replicas consume.
+
+| | Saturation | Steady state |
+|---|---|---|
+| Events pushed | 10,000 | 9,000 |
+| Ingest accepted | 397.2 events/s | 79.1 events/s |
+| Pipeline drain rate | **214.0 alerts/s** | 79.8 alerts/s |
+| Event-to-alert p50 | 4,579 ms | **982 ms** |
+| Event-to-alert p95 | 20,034 ms | **1,317 ms** |
+| Event-to-alert p99 | 22,988 ms | **1,437 ms** |
+| Event-to-alert max | 23,571 ms | 1,638 ms |
+| Peak consumer lag | 3,059 messages | 0 messages |
+| Lag after drain | 0 messages | 0 messages |
+| Dead-letter rate | 0.00 | 0.00 |
+| Events that produced no alert | 0 | 0 |
+| Events that produced more than one alert | 0 | 0 |
+
+**Per-pod CPU and memory were not measured on this deployment.** `kubectl top`
+needs metrics-server and kind does not ship one, so the harness recorded the
+absence rather than a zero. The committed JSON carries empty `containers`
+objects for exactly that reason.
+
+Two fusion replicas across three partitions drained 214 alerts/s against
+compose's 177 on the same laptop, sharing it with three brokers and a
+three-node control plane. The comparison is indicative, not a scaling law:
+kind nodes are containers on the same kernel, so this is not two machines'
+worth of hardware.
+
+## Failure injection: killing a fusion replica mid-stream
+
+`scripts/chaos/fusion_restart.py`, run against the Kubernetes deployment above
+on 2026-09-27. 6,000 events paced at 100/s; one fusion pod destroyed with
+`--grace-period=0 --force` 24.3 seconds in, with 1,840 alerts already written.
+
+| | |
+|---|---|
+| Events accepted by ingest | 6,000 |
+| Alert rows after recovery | 6,000 |
+| Events that produced no alert | 0 |
+| Events that produced more than one alert | 0 |
+| Time for the backlog to clear after the kill | 5.4 s |
+
+The assertion is made against PostgreSQL, not against anything the replacement
+pod reports about itself. Two mechanisms make it hold, and a regression in
+either shows up in a different column: the consumer commits offsets only after
+a message is fully processed, so a kill re-delivers rather than losing
+(missing count), and the alert sink inserts under a per-tenant dedup-hash
+guard, so the re-delivery does not become a second row (duplicate count).
+
+## Running it yourself
+
+```bash
+make up
+make ingest-token # mint a credential
+
+AISOC_INGEST_TOKEN=<token> python3 scripts/perf/load_harness.py \
+ --target compose --events 20000 --workers 8
+
+AISOC_INGEST_TOKEN=<token> python3 scripts/perf/load_harness.py \
+ --target compose --events 12000 --target-eps 120 # steady state
+```
+
+For Kubernetes, see [Reference HA deployment](./ha-deployment.md).
+
+## What CI enforces, and what it does not
+
+`.github/workflows/perf.yml` runs three things:
+
+1. the in-process fusion hot-path harness with a generous regression floor;
+2. the storage cost model drift check;
+3. this end-to-end harness against a Compose stack, nightly and on demand,
+ with a floor far below the figures above.
+
+The floors exist to catch a catastrophic regression, such as an I/O call
+appearing on the promotion hot path. They are deliberately not set near the
+measured values: GitHub runners are shared, throttled and noisy, and a gate
+that fires on runner jitter gets disabled within a week. **A passing perf job
+is not evidence that any number on this page still holds on your hardware.**
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index b07c5a48a..ee4c1346a 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -200,6 +200,8 @@ const sidebars: SidebarsConfig = {
"operations/mcp-client",
"operations/codespaces",
"operations/theming",
+ "operations/ha-deployment",
+ "operations/performance",
"operations/upgrades",
"operations/notifications",
"operations/action-approvals",
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 51d4bf99f..571ace247 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -206,6 +206,10 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| An agent is offered only the tools whose backend the tenant has configured | `plans/aisoc_gap_closure_plan.plan.md` (4.3); `apps/docs/docs/operations/agent-vendor-tools.md` (Only what you have connected is offered) | `ci.yml` agents job (`test_customer_tools.py` - a tenant with a Splunk and an Okta gets exactly `siem_indicator_search` and `identity_user_activity` and no EDR tools; a tenant with nothing connected gets **no** tools and two separate gap sentences, both asserted present in the findings; an unreachable API binds nothing and says "could not determine", asserted to appear in the model's prompt and not only in the reader's findings, because a note only the reader sees means the model reasoned without it) + `ci.yml` gates job (`check_agent_read_tools.py` compares the API's `AGENT_READ_CAPABILITIES` against the contract's READ_ONLY set, the executor list and the parameter allowlist, and compares the two indicator vocabularies across the agents and api trees in both directions; proven able to fail by exposing `isolate_host` and by drifting one vocabulary) | GATED | Advertisement is per connector **type**, not per instance: a tenant with two Splunks is offered one SIEM tool and the federated layer fans out to both, which is the existing behaviour of that endpoint |
| A model never composes SPL, KQL or ES-QL query text against a customer's SIEM | `plans/aisoc_gap_closure_plan.plan.md` (4.1); `apps/docs/docs/operations/agent-vendor-tools.md` (The model never writes a query) | `ci.yml` agents job (`test_customer_tools.py` asserts on the **JSON schema the model is handed**, not on the implementation, since the schema is what constrains a model: no property named query, search, spl, kql, esql, sql, free_text, field, filter, where or index on any tool, every property typed `string` or `integer` so a query cannot arrive as structured data, and `indicator_type` a closed sorted enum) + `ci.yml` api job (`test_agent_tools.py` - 23 value-shape cases in both directions, and every field token in the per-backend map asserted to match the identifier pattern the translators' own field check enforces, so a mapping that would 422 on every search cannot ship) + `ci.yml` connectors job (`Indicator.__post_init__` refuses a field name that is not an identifier, at the single choke point every translator goes through) | GATED | The field map is a reviewed table, not derived: there is no machine-readable source in this repository for what Splunk CIM calls a source address. The alternative, letting the model name the field, is the thing the boundary exists to prevent |
| Every tool call an investigation makes is in the Investigation Ledger | `plans/aisoc_gap_closure_plan.plan.md` (rules for every phase, LLM calls) | `ci.yml` agents job (`test_deep_investigation_customer_tools.py` captures what the driver hands `ledger.record_event` at the ledger's own function boundary and asserts one `tool_call` row per call in the trace, carrying the tool name **and its arguments**, because "the ledger shows every call" means an auditor can answer which host was read. Sequence numbers are asserted distinct and at or above 10,000: `record_event` carries `ON CONFLICT (run_id, seq) DO NOTHING`, so a collision with the graph runner's own numbering would be a silently dropped row, which is worse than an error because the ledger still looks complete) | GATED | `run_with_tools` built a trace and nothing carried it anywhere durable, so this is new rather than newly gated. The write is best-effort by design: a ledger failure must not take a completed investigation down, and `ledger_rows` on the result reports how many rows landed so "nothing to record" is distinguishable from "the ledger is not configured" |
+| Sustained throughput and event-to-alert latency are measured end to end, on a named machine, on a named date | `apps/docs/docs/operations/performance.md`; `docs/perf/results/*.json` | `perf.yml :: published-results` (`check_perf_results.py`: every committed result must carry `measured_at` beginning with an ISO date, a `hardware` block naming a CPU, a container runtime or a CI runner rather than a bare core count, `not_a_production_slo: true` and disclaimer prose; the filename must begin with its own measurement date; and the docs page must mention every date a result carries, so the page cannot drift into presenting old figures under a new heading. Self-tested by injecting each of those nine violations and requiring each to be caught) + `perf.yml :: end-to-end` (the harness drives the real Compose spine nightly with `--assert-eps-floor`, `--assert-p95-ceiling-ms` and `--assert-no-loss`) + `ci.yml :: python-test` (root) `test_load_harness_contract.py` | GATED | The floors are two orders of magnitude below the published figures, deliberately: a shared GitHub runner is not the machine the numbers came off, and a gate tuned near a measurement flaps and gets disabled. A green perf job proves no catastrophic regression, not that any published figure still holds |
+| A performance figure that was not measured reads "not measured", never `0` | `scripts/perf/load_harness.py`; `apps/docs/docs/operations/performance.md` (kind per-pod usage) | `perf.yml :: published-results` (`check_perf_results.py` rejects an unmeasured metric that carries a `value` key and one that carries no reason, and separately asserts a **measured** zero survives, since zero dead letters and zero drained lag are real results) + `ci.yml :: python-test` (root) `test_load_harness_contract.py` (the serialised form is asserted, because the renderer downstream sees JSON rather than the dataclass) | GATED | The kind run genuinely has no per-pod CPU or memory figures: `kubectl top` needs metrics-server and kind ships none. The committed JSON records the absence and the page says so in the same paragraph as the table |
+| A fusion replica can be destroyed mid-stream with no event lost and none duplicated | `apps/docs/docs/operations/ha-deployment.md`; `apps/docs/docs/operations/performance.md` (failure injection) | `scripts/chaos/fusion_restart.py` (asserts against the `alerts` table in PostgreSQL, never against anything the replacement pod reports about itself: every sequence number ingest accepted must appear exactly once, and a missing one and a repeated one fail separately and are named). Self-tested in both directions, including the case where a loss and a duplicate cancel out in the row count. Run against the Kubernetes deployment on 2026-09-27; the result is committed at `docs/perf/results/2026-09-27-kind-chaos.json` and `perf.yml :: published-results` requires it to carry a verdict | GATED | The self-test and the committed result are gated; the **execution** against a live cluster is not on a CI trigger, because it needs a three-node cluster with two fusion replicas and published images. `docs/audit/REPOSITORY_REALITY.md` records the date and shape of the run that was performed rather than implying it happens continuously |
+| A Helm install connects the event spine, rather than installing every object and consuming nothing | `infra/helm/aisoc/values-ha.yaml`; `apps/docs/docs/operations/ha-deployment.md` | `helm.yml :: render` (`KAFKA_BOOTSTRAP_SERVERS` is asserted present in the rendered ConfigMap and to resolve to the release's own brokers when the chart deploys them; a three-replica render is asserted to carry all three KRaft quorum voters; `ueba.enabled=false` is asserted to render no UEBA object, which it previously did) | GATED | Rendering is gated. That the brokers then form a quorum and fusion attaches was exercised on kind on 2026-09-27 and is recorded as such, not as a continuous check |
| A cross-service route this program adds is asserted against the URL the serving side actually serves | `GAP_CLOSURE_PROGRESS.md` (D16) | `ci.yml` api job (`test_agent_tools.py` parses `services/api/app/main.py`, `api/v1/router.py` and the endpoint module with `ast`, composes all three prefix levels, and asserts each literal the agents service builds is in the served set. Proven able to fail from **both** sides: dropping `/api/v1` from the client's path, and renaming the router's own prefix. The helper raises rather than returning an empty set, so a parser that stopped matching cannot certify nothing. Also asserts the `impact` field the API filters on exists on `LiveActionDescriptor` **and** is populated from the contract rather than left at its default) | GATED | Covers the two routes this phase adds and the actions discovery route it consumes. It is not a repository-wide scan: the general version would need every client's URL construction to be statically resolvable, and several build theirs from settings |
| A tenant can author an investigation skill in the console and it changes the plan on matching alerts | `apps/docs/docs/console/tenant-skills.md`; `plans/aisoc_gap_closure_plan.plan.md` (6.1, 6.2) | `ci.yml` agents job (`test_tenant_skill_investigation.py::test_done_when_a_skill_changes_the_investigation_plan_on_a_matching_alert`: one alert run twice through the real `run_deep_investigation`, everything held constant except whether the tenant has an active skill, asserting on the **system prompt the tool loop was handed** rather than on the verdict, because a verdict can be unchanged by a plan that did change. The built-in the alert would otherwise select is asserted by name, so "the skill won" and "nothing selected anything" are told apart) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py`) | GATED | A skill supplies the plan **and** the triage guidance. A skill that only changed the pivot plan could not be backtested at all: the replay grades triage verdicts, so the delta would read zero on every run |
| A skill may only name a tool that tenant's agent can actually call | `apps/docs/docs/console/tenant-skills.md` (expected_pivots is validated against your tools) | `ci.yml` api job (`test_tenant_skills.py::TestToolValidation`: the inventory is built from the tenant's **enabled** MCP servers only, so a registered-but-disabled server, an empty allowlist and another tenant's server each contribute nothing; a misspelt built-in and an un-allowlisted MCP tool get different messages because the author's next action differs) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` compares `BUILTIN_PIVOTS` against the agents service's `KNOWN_PIVOTS` in **both** directions; proven able to fail by deleting a pivot from each side in turn) | GATED | Phase 4.3's per-tenant vendor-read advertisement does not exist yet, so the inventory is the built-in lake pivots plus Phase 5.2's MCP allowlists. A pivot naming a vendor read verb is refused with a sentence saying the surface is not built, rather than silently accepted |
@@ -239,7 +243,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- GATED: 216
+- GATED: 220
- PARTIAL: 8
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/docs/audit/REPOSITORY_REALITY.md b/docs/audit/REPOSITORY_REALITY.md
index 9eb166e6e..9ee4057c8 100644
--- a/docs/audit/REPOSITORY_REALITY.md
+++ b/docs/audit/REPOSITORY_REALITY.md
@@ -259,7 +259,7 @@ unless `AISOC_ALLOW_SEED=1`.
| Component | Status |
|---|---|
-| `services/demo-producer` | **DEMO-ONLY**. Emits randomised vendor events into the real ingest API. Not in any compose profile; invoked manually. |
+| `services/demo-producer` | **DEMO-ONLY** in its default mode: randomised vendor events into the real ingest API, not in any compose profile, invoked manually. `--load` is **WORKING** and is not demo data: it is the generator `scripts/perf/load_harness.py` drives, and its events are attributable per event so the harness can time each one to the alert it became. |
| `seed_demo.py` | **DEMO-ONLY**. 15 hand-written incidents plus randomised alerts. |
| `services/agents/app/api/hunt_search.py` | **DEMO-ONLY** but honest — returns `source: "sample"` and a notice saying it does not query the lake. |
| `services/agents/app/api/copilot.py` | **PARTIAL** — real LLM path with a key; returns `source: "template"` and a notice without one. |
@@ -275,8 +275,36 @@ Stated rather than guessed:
available. The deterministic offline path was exercised. Every published
benchmark row is labelled `substrate: true` and must not be read as live
agent accuracy.
-- **Kubernetes/Helm deployment** was not exercised in this audit. The chart
- renders; whether it runs was not tested here.
+- **Kubernetes/Helm deployment: partly exercised on 2026-09-27, and only on
+ kind.** The chart was installed on a three-node kind cluster (Kubernetes
+ v1.34.0) on an Apple M5 Max with 8 CPUs and 15.6 GiB allocated to the
+ container runtime, using `values-ha.yaml` plus `ci/kind-values.yaml`. Three
+ Kafka brokers formed a KRaft quorum, two ingest and two fusion replicas came
+ up, the migration chain applied, 10,000 events pushed through the public
+ ingest endpoint all became alert rows, and a fusion pod destroyed mid-stream
+ cost neither a lost event nor a duplicated one. Figures:
+ `apps/docs/docs/operations/performance.md`.
+
+ **UNVERIFIED, in the same breath:** no managed Kubernetes service (EKS, GKE,
+ AKS) and no bare-metal cluster has been tried; kind nodes are containers on
+ one kernel, so this is not multi-machine evidence; no ingress controller or
+ cloud load balancer was in front of the release; PersistentVolumeClaims were
+ switched off for the run; NetworkPolicy enforcement needs a CNI that
+ implements it and was not exercised; managed PostgreSQL and ClickHouse were
+ not used, the run pointed at single ephemeral pods; and the longest run was
+ a few minutes, so nothing is known about sustained operation, compaction,
+ log growth or rolling upgrades. **"The chart installs and survives a pod
+ kill on kind" is not "Kubernetes is production-ready."**
+
+ Four defects were found by running it, none of which rendering could have
+ shown: `KAFKA_BOOTSTRAP_SERVERS` was set on the UEBA deployment and nowhere
+ else, so ingest and fusion defaulted to `localhost:9092` and the spine was
+ installed but not connected; the first batch after an install was lost to
+ Kafka auto-creation; readiness probes pointed at `/health`, which answers
+ 200 regardless of whether the consumer is attached, instead of `/readyz`,
+ which reports the subscription; and `ueba.enabled` had no reader, so
+ switching UEBA off still scheduled it. All four are fixed and gated by
+ `helm.yml`.
- **Whether migrations 050–053 apply** on an existing volume was not traced.
Compose mounts `services/api/migrations` as `docker-entrypoint-initdb.d`,
which runs only on a *fresh* volume. On a clean install the schema is
diff --git a/docs/perf/results/2026-09-27-compose-saturation.json b/docs/perf/results/2026-09-27-compose-saturation.json
new file mode 100644
index 000000000..5dad524be
--- /dev/null
+++ b/docs/perf/results/2026-09-27-compose-saturation.json
@@ -0,0 +1,412 @@
+{
+ "schema": "aisoc.load_harness/v1",
+ "measured_at": "2026-09-27T13:45:36+00:00",
+ "hardware": {
+ "os": "Darwin 25.5.0",
+ "arch": "arm64",
+ "python": "3.14.3",
+ "cpu_count": 18,
+ "cpu": "Apple M5 Max",
+ "memory_bytes": "137438953472",
+ "container_runtime": "docker 29.5.2",
+ "runtime_cpus": "8",
+ "runtime_memory_bytes": "16732614656"
+ },
+ "deployment": "docker-compose",
+ "not_a_production_slo": true,
+ "slo_disclaimer": "These are measurements of one deployment on the hardware named above, on the date named above. They are not a service-level objective and no support commitment is derived from them. Sustained throughput on other hardware, other storage and other event mixes will differ. The regression floors in perf.yml are set well below the measured values so they fire on a catastrophic regression rather than on runner jitter.",
+ "run": {
+ "run_id": "p90516615",
+ "attempted_events": 20000,
+ "accepted_events": 20000,
+ "alerts_observed": 20000,
+ "distinct_events_alerted": 20000,
+ "missing_events": 0,
+ "duplicate_alert_rows": 0,
+ "push_wall_seconds": 50.33892575,
+ "drain_wall_seconds": 65.44419622421265,
+ "drain_settled": true,
+ "clock_offset_seconds": -0.11746048927307129,
+ "clock_offset_spread_seconds": 0.08669662475585938,
+ "producer": {
+ "run_id": "p90516615",
+ "mode": "load",
+ "marker_prefix": "aisoc-load",
+ "ingest_url": "http://localhost:8081/v1/ingest/batch",
+ "tenant": "00000000-0000-0000-0000-000000000001",
+ "started_at": "2026-09-27T13:43:36.054453Z",
+ "ended_at": "2026-09-27T13:44:26.39337875Z",
+ "wall_seconds": 50.33892575,
+ "workers": 8,
+ "batch_size": 50,
+ "target_eps": 0,
+ "requested_events": 20000,
+ "attempted_events": 20000,
+ "accepted_events": 20000,
+ "rejected_events": 0,
+ "refused_events": 0,
+ "transport_error_events": 0,
+ "accepted_eps": 397.3068495606504,
+ "http_status_counts": {
+ "200": 400
+ },
+ "seq_low": 0,
+ "seq_high": 19999
+ },
+ "total_wall_seconds": 121.02021980285645
+ },
+ "metrics": {
+ "consumer_lag_drained": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 0.0
+ },
+ "consumer_lag_in_flight": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 10759.0
+ },
+ "dead_letter_rate": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 20000,
+ "value": 0.0
+ },
+ "delivery_ratio": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 20000,
+ "value": 1.0
+ },
+ "ingest_accepted_eps": {
+ "unit": "events/s",
+ "measured": true,
+ "samples": 20000,
+ "value": 397.3068495606504
+ },
+ "latency_max_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 20000,
+ "value": 64712.96739578247
+ },
+ "latency_p50_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 20000,
+ "value": 30415.149688720703
+ },
+ "latency_p95_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 20000,
+ "value": 60707.441568374634
+ },
+ "latency_p99_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 20000,
+ "value": 63775.53939819336
+ },
+ "pipeline_eps": {
+ "unit": "alerts/s",
+ "measured": true,
+ "samples": 20000,
+ "value": 176.85720869640932
+ }
+ },
+ "resources": [
+ {
+ "at": "2026-09-27T13:44:27+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.16%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "61.27%",
+ "memory": "74.06MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.06%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.00%",
+ "memory": "28.71MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "82.39%",
+ "memory": "453.5MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "7.02%",
+ "memory": "96.61MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:44:29+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.09%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "59.90%",
+ "memory": "74.16MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.06%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.00%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "10.96%",
+ "memory": "454.2MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "6.94%",
+ "memory": "97.67MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:44:36+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.11%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "61.73%",
+ "memory": "74.82MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.07%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.00%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "13.08%",
+ "memory": "454.9MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "7.45%",
+ "memory": "101.3MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:44:44+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.11%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "61.95%",
+ "memory": "73.16MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.07%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.02%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "18.67%",
+ "memory": "466.7MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "7.33%",
+ "memory": "105.1MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:44:51+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.14%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "60.61%",
+ "memory": "73.52MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.06%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.02%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "12.21%",
+ "memory": "473.6MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "30.75%",
+ "memory": "108.6MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:44:58+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.12%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "64.09%",
+ "memory": "75.93MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.06%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.03%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "25.50%",
+ "memory": "503.7MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "7.83%",
+ "memory": "112.1MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:45:06+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.13%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "63.82%",
+ "memory": "74.46MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.08%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.00%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "12.47%",
+ "memory": "486.7MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "7.69%",
+ "memory": "115.3MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:45:13+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.11%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "61.83%",
+ "memory": "75.12MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "9.82%",
+ "memory": "201.1MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.00%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "11.10%",
+ "memory": "496.7MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "7.31%",
+ "memory": "118.3MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:45:20+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "2.63%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "62.54%",
+ "memory": "77.34MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.64%",
+ "memory": "201.2MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.02%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "10.98%",
+ "memory": "517.6MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "8.89%",
+ "memory": "122.5MiB / 15.58GiB"
+ }
+ }
+ },
+ {
+ "at": "2026-09-27T13:45:27+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.12%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "64.99%",
+ "memory": "76.35MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.06%",
+ "memory": "201.2MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.02%",
+ "memory": "22.22MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "12.76%",
+ "memory": "519.5MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "7.74%",
+ "memory": "125.9MiB / 15.58GiB"
+ }
+ }
+ }
+ ]
+}
diff --git a/docs/perf/results/2026-09-27-compose-steady.json b/docs/perf/results/2026-09-27-compose-steady.json
new file mode 100644
index 000000000..21a3495a7
--- /dev/null
+++ b/docs/perf/results/2026-09-27-compose-steady.json
@@ -0,0 +1,151 @@
+{
+ "schema": "aisoc.load_harness/v1",
+ "measured_at": "2026-09-27T13:48:29+00:00",
+ "hardware": {
+ "os": "Darwin 25.5.0",
+ "arch": "arm64",
+ "python": "3.14.3",
+ "cpu_count": 18,
+ "cpu": "Apple M5 Max",
+ "memory_bytes": "137438953472",
+ "container_runtime": "docker 29.5.2",
+ "runtime_cpus": "8",
+ "runtime_memory_bytes": "16732614656"
+ },
+ "deployment": "docker-compose",
+ "not_a_production_slo": true,
+ "slo_disclaimer": "These are measurements of one deployment on the hardware named above, on the date named above. They are not a service-level objective and no support commitment is derived from them. Sustained throughput on other hardware, other storage and other event mixes will differ. The regression floors in perf.yml are set well below the measured values so they fire on a catastrophic regression rather than on runner jitter.",
+ "run": {
+ "run_id": "p90516752",
+ "attempted_events": 12000,
+ "accepted_events": 12000,
+ "alerts_observed": 12000,
+ "distinct_events_alerted": 12000,
+ "missing_events": 0,
+ "duplicate_alert_rows": 0,
+ "push_wall_seconds": 150.643365083,
+ "drain_wall_seconds": 0.14412212371826172,
+ "drain_settled": true,
+ "clock_offset_seconds": -0.10294818878173828,
+ "clock_offset_spread_seconds": 0.01700878143310547,
+ "producer": {
+ "run_id": "p90516752",
+ "mode": "load",
+ "marker_prefix": "aisoc-load",
+ "ingest_url": "http://localhost:8081/v1/ingest/batch",
+ "tenant": "00000000-0000-0000-0000-000000000001",
+ "started_at": "2026-09-27T13:45:53.040041Z",
+ "ended_at": "2026-09-27T13:48:23.683406083Z",
+ "wall_seconds": 150.643365083,
+ "workers": 4,
+ "batch_size": 20,
+ "target_eps": 120,
+ "requested_events": 12000,
+ "attempted_events": 12000,
+ "accepted_events": 12000,
+ "rejected_events": 0,
+ "refused_events": 0,
+ "transport_error_events": 0,
+ "accepted_eps": 79.65833738106129,
+ "http_status_counts": {
+ "200": 600
+ },
+ "seq_low": 0,
+ "seq_high": 11999
+ },
+ "total_wall_seconds": 156.68188285827637
+ },
+ "metrics": {
+ "consumer_lag_drained": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 0.0
+ },
+ "consumer_lag_in_flight": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 0.0
+ },
+ "dead_letter_rate": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 12000,
+ "value": 0.0
+ },
+ "delivery_ratio": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 12000,
+ "value": 1.0
+ },
+ "ingest_accepted_eps": {
+ "unit": "events/s",
+ "measured": true,
+ "samples": 12000,
+ "value": 79.65833738106129
+ },
+ "latency_max_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 12000,
+ "value": 1272.6917266845703
+ },
+ "latency_p50_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 12000,
+ "value": 976.099967956543
+ },
+ "latency_p95_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 12000,
+ "value": 1090.498924255371
+ },
+ "latency_p99_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 12000,
+ "value": 1155.9815406799316
+ },
+ "pipeline_eps": {
+ "unit": "alerts/s",
+ "measured": true,
+ "samples": 12000,
+ "value": 80.08123818883172
+ }
+ },
+ "resources": [
+ {
+ "at": "2026-09-27T13:48:25+00:00",
+ "containers": {
+ "agents": {
+ "cpu": "0.14%",
+ "memory": "155.2MiB / 15.58GiB"
+ },
+ "fusion": {
+ "cpu": "0.16%",
+ "memory": "80.21MiB / 15.58GiB"
+ },
+ "api": {
+ "cpu": "0.08%",
+ "memory": "201.2MiB / 15.58GiB"
+ },
+ "ingest": {
+ "cpu": "0.00%",
+ "memory": "23.32MiB / 15.58GiB"
+ },
+ "kafka": {
+ "cpu": "0.57%",
+ "memory": "758.3MiB / 1.5GiB"
+ },
+ "postgres": {
+ "cpu": "0.01%",
+ "memory": "159.6MiB / 15.58GiB"
+ }
+ }
+ }
+ ]
+}
diff --git a/docs/perf/results/2026-09-27-kind-chaos.json b/docs/perf/results/2026-09-27-kind-chaos.json
new file mode 100644
index 000000000..1f0a5785a
--- /dev/null
+++ b/docs/perf/results/2026-09-27-kind-chaos.json
@@ -0,0 +1,27 @@
+{
+ "schema": "aisoc.chaos_fusion_restart/v1",
+ "measured_at": "2026-09-27T14:21:46+00:00",
+ "deployment": "kubernetes",
+ "run_id": "c90518825",
+ "replica_killed": "aisoc-alert-fusion-8dcff55cd-p8rm9",
+ "replicas_before": [
+ "aisoc-alert-fusion-8dcff55cd-p8rm9",
+ "aisoc-alert-fusion-8dcff55cd-sg4gm"
+ ],
+ "replicas_after": [
+ "aisoc-alert-fusion-8dcff55cd-dg6k9",
+ "aisoc-alert-fusion-8dcff55cd-sg4gm"
+ ],
+ "replica_replaced": true,
+ "killed_at_offset_seconds": 24.3,
+ "alerts_stored_when_killed": 1840,
+ "drain_seconds": 5.4,
+ "accepted_events": 6000,
+ "alert_rows": 6000,
+ "distinct_events_alerted": 6000,
+ "missing_count": 0,
+ "duplicate_count": 0,
+ "missing_sample": [],
+ "duplicated_sample": [],
+ "verdict": "no loss, no duplicates"
+}
diff --git a/docs/perf/results/2026-09-27-kind-saturation.json b/docs/perf/results/2026-09-27-kind-saturation.json
new file mode 100644
index 000000000..b21af150b
--- /dev/null
+++ b/docs/perf/results/2026-09-27-kind-saturation.json
@@ -0,0 +1,146 @@
+{
+ "schema": "aisoc.load_harness/v1",
+ "measured_at": "2026-09-27T14:16:52+00:00",
+ "hardware": {
+ "os": "Darwin 25.5.0",
+ "arch": "arm64",
+ "python": "3.14.3",
+ "cpu_count": 18,
+ "cpu": "Apple M5 Max",
+ "memory_bytes": "137438953472",
+ "container_runtime": "docker 29.5.2",
+ "runtime_cpus": "8",
+ "runtime_memory_bytes": "16732614656"
+ },
+ "deployment": "kubernetes",
+ "not_a_production_slo": true,
+ "slo_disclaimer": "These are measurements of one deployment on the hardware named above, on the date named above. They are not a service-level objective and no support commitment is derived from them. Sustained throughput on other hardware, other storage and other event mixes will differ. The regression floors in perf.yml are set well below the measured values so they fire on a catastrophic regression rather than on runner jitter.",
+ "run": {
+ "run_id": "p90518558",
+ "attempted_events": 10000,
+ "accepted_events": 10000,
+ "alerts_observed": 10000,
+ "distinct_events_alerted": 10000,
+ "missing_events": 0,
+ "duplicate_alert_rows": 0,
+ "push_wall_seconds": 25.173491458,
+ "drain_wall_seconds": 25.746234893798828,
+ "drain_settled": true,
+ "clock_offset_seconds": -0.08023977279663086,
+ "clock_offset_spread_seconds": 0.003902912139892578,
+ "producer": {
+ "run_id": "p90518558",
+ "mode": "load",
+ "marker_prefix": "aisoc-load",
+ "ingest_url": "http://127.0.0.1:30081/v1/ingest/batch",
+ "tenant": "00000000-0000-0000-0000-000000000001",
+ "started_at": "2026-09-27T14:15:58.527675Z",
+ "ended_at": "2026-09-27T14:16:23.701166458Z",
+ "wall_seconds": 25.173491458,
+ "workers": 8,
+ "batch_size": 50,
+ "target_eps": 0,
+ "requested_events": 10000,
+ "attempted_events": 10000,
+ "accepted_events": 10000,
+ "rejected_events": 0,
+ "refused_events": 0,
+ "transport_error_events": 0,
+ "accepted_eps": 397.2432674539492,
+ "http_status_counts": {
+ "200": 200
+ },
+ "seq_low": 0,
+ "seq_high": 9999
+ },
+ "total_wall_seconds": 54.75446105003357
+ },
+ "metrics": {
+ "consumer_lag_drained": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 0.0
+ },
+ "consumer_lag_in_flight": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 3059.0
+ },
+ "dead_letter_rate": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 10000,
+ "value": 0.0
+ },
+ "delivery_ratio": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 10000,
+ "value": 1.0
+ },
+ "ingest_accepted_eps": {
+ "unit": "events/s",
+ "measured": true,
+ "samples": 10000,
+ "value": 397.2432674539492
+ },
+ "latency_max_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 10000,
+ "value": 23570.921421051025
+ },
+ "latency_p50_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 10000,
+ "value": 4579.069137573242
+ },
+ "latency_p95_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 10000,
+ "value": 20033.623218536377
+ },
+ "latency_p99_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 10000,
+ "value": 22988.31820487976
+ },
+ "pipeline_eps": {
+ "unit": "alerts/s",
+ "measured": true,
+ "samples": 10000,
+ "value": 214.0133499546145
+ }
+ },
+ "resources": [
+ {
+ "at": "2026-09-27T14:16:25+00:00",
+ "containers": {}
+ },
+ {
+ "at": "2026-09-27T14:16:25+00:00",
+ "containers": {}
+ },
+ {
+ "at": "2026-09-27T14:16:30+00:00",
+ "containers": {}
+ },
+ {
+ "at": "2026-09-27T14:16:35+00:00",
+ "containers": {}
+ },
+ {
+ "at": "2026-09-27T14:16:40+00:00",
+ "containers": {}
+ },
+ {
+ "at": "2026-09-27T14:16:45+00:00",
+ "containers": {}
+ }
+ ]
+}
diff --git a/docs/perf/results/2026-09-27-kind-steady.json b/docs/perf/results/2026-09-27-kind-steady.json
new file mode 100644
index 000000000..85f288e7a
--- /dev/null
+++ b/docs/perf/results/2026-09-27-kind-steady.json
@@ -0,0 +1,126 @@
+{
+ "schema": "aisoc.load_harness/v1",
+ "measured_at": "2026-09-27T14:18:57+00:00",
+ "hardware": {
+ "os": "Darwin 25.5.0",
+ "arch": "arm64",
+ "python": "3.14.3",
+ "cpu_count": 18,
+ "cpu": "Apple M5 Max",
+ "memory_bytes": "137438953472",
+ "container_runtime": "docker 29.5.2",
+ "runtime_cpus": "8",
+ "runtime_memory_bytes": "16732614656"
+ },
+ "deployment": "kubernetes",
+ "not_a_production_slo": true,
+ "slo_disclaimer": "These are measurements of one deployment on the hardware named above, on the date named above. They are not a service-level objective and no support commitment is derived from them. Sustained throughput on other hardware, other storage and other event mixes will differ. The regression floors in perf.yml are set well below the measured values so they fire on a catastrophic regression rather than on runner jitter.",
+ "run": {
+ "run_id": "p90518621",
+ "attempted_events": 9000,
+ "accepted_events": 9000,
+ "alerts_observed": 9000,
+ "distinct_events_alerted": 9000,
+ "missing_events": 0,
+ "duplicate_alert_rows": 0,
+ "push_wall_seconds": 113.718966208,
+ "drain_wall_seconds": 0.08301973342895508,
+ "drain_settled": true,
+ "clock_offset_seconds": -0.08445167541503906,
+ "clock_offset_spread_seconds": 0.13600873947143555,
+ "producer": {
+ "run_id": "p90518621",
+ "mode": "load",
+ "marker_prefix": "aisoc-load",
+ "ingest_url": "http://127.0.0.1:30081/v1/ingest/batch",
+ "tenant": "00000000-0000-0000-0000-000000000001",
+ "started_at": "2026-09-27T14:17:01.391114Z",
+ "ended_at": "2026-09-27T14:18:55.110080208Z",
+ "wall_seconds": 113.718966208,
+ "workers": 4,
+ "batch_size": 20,
+ "target_eps": 150,
+ "requested_events": 9000,
+ "attempted_events": 9000,
+ "accepted_events": 9000,
+ "rejected_events": 0,
+ "refused_events": 0,
+ "transport_error_events": 0,
+ "accepted_eps": 79.14247112955957,
+ "http_status_counts": {
+ "200": 450
+ },
+ "seq_low": 0,
+ "seq_high": 8999
+ },
+ "total_wall_seconds": 117.22194385528564
+ },
+ "metrics": {
+ "consumer_lag_drained": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 0.0
+ },
+ "consumer_lag_in_flight": {
+ "unit": "messages",
+ "measured": true,
+ "samples": 1,
+ "value": 0.0
+ },
+ "dead_letter_rate": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 9000,
+ "value": 0.0
+ },
+ "delivery_ratio": {
+ "unit": "fraction",
+ "measured": true,
+ "samples": 9000,
+ "value": 1.0
+ },
+ "ingest_accepted_eps": {
+ "unit": "events/s",
+ "measured": true,
+ "samples": 9000,
+ "value": 79.14247112955957
+ },
+ "latency_max_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 9000,
+ "value": 1637.831449508667
+ },
+ "latency_p50_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 9000,
+ "value": 981.8544387817383
+ },
+ "latency_p95_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 9000,
+ "value": 1317.1584606170654
+ },
+ "latency_p99_ms": {
+ "unit": "ms",
+ "measured": true,
+ "samples": 9000,
+ "value": 1436.5544319152832
+ },
+ "pipeline_eps": {
+ "unit": "alerts/s",
+ "measured": true,
+ "samples": 9000,
+ "value": 79.81947954895244
+ }
+ },
+ "resources": [
+ {
+ "at": "2026-09-27T14:18:56+00:00",
+ "containers": {}
+ }
+ ]
+}
diff --git a/infra/helm/aisoc/ci/datastores.yaml b/infra/helm/aisoc/ci/datastores.yaml
new file mode 100644
index 000000000..0c756cf18
--- /dev/null
+++ b/infra/helm/aisoc/ci/datastores.yaml
@@ -0,0 +1,122 @@
+# Datastores for exercising the chart on kind or k3d. NOT a production shape.
+#
+# The chart deliberately does not run PostgreSQL or Redis in a highly
+# available configuration (see values-ha.yaml). These single pods stand in for
+# the managed services a real deployment points at, so that
+# `scripts/chaos/fusion_restart.py` and `scripts/perf/load_harness.py` have
+# something to run against. Storage is ephemeral and the passwords are in
+# plain text, both of which disqualify this from anything but a test cluster.
+#
+# The two-role split is preserved because it is what the chart expects and
+# what row-level security depends on: `aisoc` owns the schema and applies
+# migrations, `aisoc_app` is the DML-only runtime role that policies actually
+# filter. Collapsing them here would make a chart install that is subtly
+# unlike a real one, which is how the RLS-was-decorative defect survived.
+apiVersion: v1
+kind: Service
+metadata:
+ name: postgres
+ labels:
+ app.kubernetes.io/component: postgres
+spec:
+ selector:
+ app.kubernetes.io/component: postgres
+ ports:
+ - port: 5432
+ targetPort: 5432
+---
+apiVersion: apps/v1
+kind: StatefulSet
+metadata:
+ name: postgres
+spec:
+ serviceName: postgres
+ replicas: 1
+ selector:
+ matchLabels:
+ app.kubernetes.io/component: postgres
+ template:
+ metadata:
+ labels:
+ app.kubernetes.io/component: postgres
+ spec:
+ containers:
+ - name: postgres
+ image: postgres:16-alpine
+ imagePullPolicy: IfNotPresent
+ env:
+ - name: POSTGRES_USER
+ value: aisoc
+ - name: POSTGRES_PASSWORD
+ value: aisoc_dev_secret
+ - name: POSTGRES_DB
+ value: aisoc
+ - name: PGDATA
+ value: /var/lib/postgresql/data/pgdata
+ ports:
+ - containerPort: 5432
+ readinessProbe:
+ exec:
+ command: ["pg_isready", "-U", "aisoc", "-d", "aisoc"]
+ initialDelaySeconds: 5
+ periodSeconds: 5
+ resources:
+ requests:
+ cpu: 100m
+ memory: 256Mi
+ limits:
+ cpu: 1000m
+ memory: 1Gi
+ volumeMounts:
+ - name: data
+ mountPath: /var/lib/postgresql/data
+ volumes:
+ - name: data
+ emptyDir: {}
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: redis
+ labels:
+ app.kubernetes.io/component: redis
+spec:
+ selector:
+ app.kubernetes.io/component: redis
+ ports:
+ - port: 6379
+ targetPort: 6379
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: redis
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app.kubernetes.io/component: redis
+ template:
+ metadata:
+ labels:
+ app.kubernetes.io/component: redis
+ spec:
+ containers:
+ - name: redis
+ image: redis:7-alpine
+ imagePullPolicy: IfNotPresent
+ args: ["redis-server", "--requirepass", "redis_dev_secret"]
+ ports:
+ - containerPort: 6379
+ readinessProbe:
+ exec:
+ command: ["redis-cli", "-a", "redis_dev_secret", "ping"]
+ initialDelaySeconds: 3
+ periodSeconds: 5
+ resources:
+ requests:
+ cpu: 50m
+ memory: 64Mi
+ limits:
+ cpu: 500m
+ memory: 256Mi
diff --git a/infra/helm/aisoc/ci/kind-values.yaml b/infra/helm/aisoc/ci/kind-values.yaml
new file mode 100644
index 000000000..4b5caa1f3
--- /dev/null
+++ b/infra/helm/aisoc/ci/kind-values.yaml
@@ -0,0 +1,124 @@
+# The slice of the chart a kind or k3d node can actually run, layered on
+# values-ha.yaml.
+#
+# helm install aisoc infra/helm/aisoc -n aisoc \
+# -f infra/helm/aisoc/values-ha.yaml \
+# -f infra/helm/aisoc/ci/kind-values.yaml
+#
+# What it changes, and why each change is a test-rig concession rather than a
+# recommendation:
+#
+# * The three Kafka brokers stay. They are the subject of the exercise:
+# the chaos test's "no loss, no duplicates" claim rests on replication
+# factor 3 with min.insync.replicas 2, and one broker would prove nothing.
+# * Requests are cut to what three kind nodes on a laptop can schedule.
+# Production requests live in values.yaml and values-ha.yaml.
+# * Persistence is off. A kind cluster is deleted at the end of the run;
+# a PersistentVolumeClaim would outlive nothing and slow every restart.
+# * web, realtime and agents are dropped. Neither the load harness nor the
+# chaos test touches a browser or the triage worker, and their images are
+# the largest in the release.
+# * ingest is published on a NodePort so a harness outside the cluster can
+# push to it without a port-forward, which dies silently mid-run.
+
+global:
+ environment: development
+
+kafka:
+ deploy:
+ enabled: true
+ replicaCount: 3
+ replicationFactor: 3
+ minInsyncReplicas: 2
+ numPartitions: 3
+ persistence:
+ enabled: false
+ resources:
+ requests:
+ cpu: 100m
+ memory: 512Mi
+ limits:
+ cpu: 1500m
+ memory: 1536Mi
+
+ingress:
+ enabled: false
+
+ueba:
+ enabled: false
+honeytokens:
+ enabled: false
+purpleTeam:
+ enabled: false
+postgresql:
+ enabled: false
+redis:
+ enabled: false
+
+services:
+ api:
+ replicaCount: 1
+ hpa:
+ enabled: false
+ pdb:
+ enabled: false
+ readinessPath: /readyz
+ resources:
+ requests:
+ cpu: 100m
+ memory: 384Mi
+ limits:
+ cpu: 1500m
+ memory: 1536Mi
+ env:
+ AISOC_DISABLE_KAFKA: "false"
+
+ ingest:
+ replicaCount: 2
+ hpa:
+ enabled: false
+ pdb:
+ enabled: false
+ containerPort: 8080
+ service:
+ type: NodePort
+ port: 8080
+ nodePort: 30081
+ resources:
+ requests:
+ cpu: 100m
+ memory: 128Mi
+ limits:
+ cpu: 1000m
+ memory: 512Mi
+ env:
+ HTTP_PORT: "8080"
+ METRICS_PORT: "9090"
+ ENV: development
+ AISOC_GRAPH_ENABLED: "false"
+
+ # Two replicas, not one: the chaos test kills a pod and the claim is that
+ # the partitions it owned are picked up without loss or duplication. With a
+ # single replica there is nothing to rebalance onto and the test would be
+ # measuring restart time.
+ alert-fusion:
+ replicaCount: 2
+ hpa:
+ enabled: false
+ pdb:
+ enabled: false
+ containerPort: 8003
+ resources:
+ requests:
+ cpu: 200m
+ memory: 512Mi
+ limits:
+ cpu: 2000m
+ memory: 2Gi
+ env:
+ AISOC_LAKE_WRITER_ENABLED: "false"
+
+ web: null
+ realtime: null
+ agents: null
+ enrichment: null
diff --git a/infra/helm/aisoc/templates/_helpers.tpl b/infra/helm/aisoc/templates/_helpers.tpl
index af2e938b7..d45428ea2 100644
--- a/infra/helm/aisoc/templates/_helpers.tpl
+++ b/infra/helm/aisoc/templates/_helpers.tpl
@@ -48,6 +48,40 @@ app.kubernetes.io/name: {{ include "aisoc.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
+{{/*
+The broker address every service in the release should dial.
+
+One definition rather than a string repeated per template: the release's own
+brokers when the chart deploys them, and whatever the operator named
+otherwise. `kafka.bootstrapServers` stays the escape hatch for a managed
+broker (MSK, Confluent Cloud, Redpanda), which is the production shape.
+*/}}
+{{- define "aisoc.kafkaBootstrap" -}}
+{{- if .Values.kafka.deploy.enabled -}}
+{{- printf "%s-kafka.%s.svc.cluster.local:9092" (include "aisoc.fullname" .) .Release.Namespace -}}
+{{- else -}}
+{{- .Values.kafka.bootstrapServers | default "kafka:9092" -}}
+{{- end -}}
+{{- end }}
+
+{{/*
+The KRaft controller quorum, as `<node-id>@<stable-dns>:9093` per broker.
+
+Every voter has to be listed on every broker or the quorum never forms, and
+the names have to be the StatefulSet's stable per-pod DNS rather than the
+client Service, which load-balances and would point a controller at a peer
+chosen at random.
+*/}}
+{{- define "aisoc.kafkaQuorumVoters" -}}
+{{- $fullname := include "aisoc.fullname" . -}}
+{{- $ns := .Release.Namespace -}}
+{{- $voters := list -}}
+{{- range $i := until (int .Values.kafka.deploy.replicaCount) -}}
+{{- $voters = append $voters (printf "%d@%s-kafka-%d.%s-kafka-headless.%s.svc.cluster.local:9093" $i $fullname $i $fullname $ns) -}}
+{{- end -}}
+{{- join "," $voters -}}
+{{- end }}
+
{{/*
Service account name
*/}}
diff --git a/infra/helm/aisoc/templates/configmap.yaml b/infra/helm/aisoc/templates/configmap.yaml
index b10ad4212..1abf9c839 100644
--- a/infra/helm/aisoc/templates/configmap.yaml
+++ b/infra/helm/aisoc/templates/configmap.yaml
@@ -10,6 +10,25 @@ data:
ENVIRONMENT: {{ .Values.global.environment | default "production" | quote }}
OTEL_EXPORTER_OTLP_ENDPOINT: {{ .Values.global.otelEndpoint | default "" | quote }}
OTEL_SERVICE_NAME: {{ include "aisoc.fullname" . | quote }}
+ {{- /*
+ The broker address, for every deployment in the release.
+
+ It was set on exactly one: ueba-deployment.yaml read
+ `.Values.kafka.bootstrapServers` and nothing else did. `services/ingest`
+ reads KAFKA_BOOTSTRAP_SERVERS (falling back to KAFKA_BROKERS) and
+ `services/fusion` reads KAFKA_BOOTSTRAP_SERVERS, both defaulting in code
+ to localhost:9092, which inside a pod resolves to the pod itself. So a
+ Helm install produced an ingest that published to nowhere and a fusion
+ that consumed nothing, with every object created, every probe green and
+ nothing in any log to say the spine was not connected. This is the same
+ shape as the Compose-era `common_env` defect recorded in the AWS notes:
+ one canonical variable, set in one place, missed everywhere else.
+
+ Both spellings are emitted because the Go service accepts either and
+ third-party sidecars in this ecosystem disagree about which is canonical.
+ */}}
+ KAFKA_BOOTSTRAP_SERVERS: {{ include "aisoc.kafkaBootstrap" . | quote }}
+ KAFKA_BROKERS: {{ include "aisoc.kafkaBootstrap" . | quote }}
{{- range $k, $v := .Values.global.extraConfig }}
{{ $k }}: {{ $v | quote }}
{{- end }}
diff --git a/infra/helm/aisoc/templates/deployment.yaml b/infra/helm/aisoc/templates/deployment.yaml
index a9ec7a8d5..bb2b69670 100644
--- a/infra/helm/aisoc/templates/deployment.yaml
+++ b/infra/helm/aisoc/templates/deployment.yaml
@@ -49,6 +49,54 @@ spec:
matchLabels:
{{- include "aisoc.selectorLabels" $ | nindent 14 }}
app.kubernetes.io/component: {{ $name }}
+ {{- if and $svc.waitForKafka $.Values.kafka.waitForBroker.enabled }}
+ {{- /*
+ Hold a consumer or producer back until a broker answers.
+
+ Without this, a cold install races: the Kafka StatefulSet is still
+ forming its controller quorum when fusion's lifespan runs, aiokafka's
+ bootstrap raises KafkaConnectionError, the worker task ends, and
+ nothing retries. The pod stays Running and /health keeps answering
+ 200, so the install looks complete with nothing consuming the spine.
+ Observed on a three-node kind cluster on 2026-09-27: every event was
+ accepted by ingest and none became an alert.
+
+ A readiness probe alone does not fix this, because Kubernetes does not
+ restart on readiness failure, by design, so that a broker fault is
+ not hidden behind a restart loop. Ordering is the chart's job.
+ */}}
+ initContainers:
+ - name: wait-for-kafka
+ image: "{{ $.Values.kafka.waitForBroker.image.repository }}:{{ $.Values.kafka.waitForBroker.image.tag }}"
+ imagePullPolicy: {{ $.Values.kafka.waitForBroker.image.pullPolicy }}
+ command: ["/bin/bash", "-c"]
+ args:
+ - |
+ set -uo pipefail
+ bootstrap="{{ include "aisoc.kafkaBootstrap" $ }}"
+ for attempt in $(seq 1 {{ $.Values.kafka.waitForBroker.attempts }}); do
+ if /opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server "$bootstrap" >/dev/null 2>&1; then
+ echo "broker reachable at $bootstrap"
+ exit 0
+ fi
+ echo "waiting for $bootstrap (attempt $attempt)"
+ sleep {{ $.Values.kafka.waitForBroker.intervalSeconds }}
+ done
+ echo "no broker answered at $bootstrap; refusing to start a consumer that would detach silently" >&2
+ exit 1
+ resources:
+ requests:
+ cpu: 50m
+ memory: 256Mi
+ limits:
+ cpu: 500m
+ memory: 768Mi
+ securityContext:
+ allowPrivilegeEscalation: false
+ capabilities:
+ drop:
+ - ALL
+ {{- end }}
containers:
- name: {{ $name }}
image: "{{ $svc.image.repository }}:{{ $svc.image.tag | default $.Chart.AppVersion }}"
diff --git a/infra/helm/aisoc/templates/kafka-statefulset.yaml b/infra/helm/aisoc/templates/kafka-statefulset.yaml
new file mode 100644
index 000000000..58dbf47c2
--- /dev/null
+++ b/infra/helm/aisoc/templates/kafka-statefulset.yaml
@@ -0,0 +1,241 @@
+{{- if .Values.kafka.deploy.enabled }}
+{{- /*
+ Three Kafka brokers, in KRaft combined mode.
+
+ Until this template the chart had no broker at all: `kafka.bootstrapServers`
+ pointed at a Service named `kafka` that nothing in the chart creates, and
+ only ueba-deployment.yaml read it. Every other pod fell through to the
+ in-code default of localhost:9092, which resolves inside a pod to the pod
+ itself, so ingest published into nothing and fusion consumed nothing, with
+ no object missing and no error at install time. `configmap.yaml` now sets
+ KAFKA_BOOTSTRAP_SERVERS for every deployment in the release.
+
+ Combined mode (broker + controller in one process) rather than dedicated
+ controllers: three pods instead of six for the same fault tolerance at this
+ size, which is what a reference deployment should cost. Separate controller
+ nodes are the right trade at a scale where a rebalance storm must not
+ contend with controller quorum, and that is a documented upgrade rather
+ than the default here.
+
+ The replication settings below are the reason a broker can be lost without
+ losing data: replication factor 3 with min.insync.replicas 2 means a write
+ is acknowledged only once it is on two brokers, so one failure costs
+ availability of neither writes nor reads. They apply to the internal topics
+ AND to auto-created ones, because every topic in this platform is
+ auto-created on first publish.
+*/}}
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "aisoc.fullname" . }}-kafka-headless
+ namespace: {{ .Release.Namespace }}
+ labels:
+ {{- include "aisoc.labels" . | nindent 4 }}
+ app.kubernetes.io/component: kafka
+spec:
+ clusterIP: None
+ # Brokers must resolve each other's stable DNS names for the controller
+ # quorum to form, and a pod is not Ready until it has joined that quorum.
+ # Without this the three pods wait for names that do not exist yet.
+ publishNotReadyAddresses: true
+ ports:
+ - name: client
+ port: 9092
+ targetPort: client
+ - name: controller
+ port: 9093
+ targetPort: controller
+ selector:
+ {{- include "aisoc.selectorLabels" . | nindent 4 }}
+ app.kubernetes.io/component: kafka
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "aisoc.fullname" . }}-kafka
+ namespace: {{ .Release.Namespace }}
+ labels:
+ {{- include "aisoc.labels" . | nindent 4 }}
+ app.kubernetes.io/component: kafka
+spec:
+ type: ClusterIP
+ ports:
+ - name: client
+ port: 9092
+ targetPort: client
+ selector:
+ {{- include "aisoc.selectorLabels" . | nindent 4 }}
+ app.kubernetes.io/component: kafka
+---
+apiVersion: policy/v1
+kind: PodDisruptionBudget
+metadata:
+ name: {{ include "aisoc.fullname" . }}-kafka
+ namespace: {{ .Release.Namespace }}
+ labels:
+ {{- include "aisoc.labels" . | nindent 4 }}
+ app.kubernetes.io/component: kafka
+spec:
+ # With replication factor 3 and min.insync.replicas 2, losing a second
+ # broker stops writes. A voluntary disruption must never be the cause.
+ maxUnavailable: 1
+ selector:
+ matchLabels:
+ {{- include "aisoc.selectorLabels" . | nindent 6 }}
+ app.kubernetes.io/component: kafka
+---
+apiVersion: apps/v1
+kind: StatefulSet
+metadata:
+ name: {{ include "aisoc.fullname" . }}-kafka
+ namespace: {{ .Release.Namespace }}
+ labels:
+ {{- include "aisoc.labels" . | nindent 4 }}
+ app.kubernetes.io/component: kafka
+spec:
+ serviceName: {{ include "aisoc.fullname" . }}-kafka-headless
+ replicas: {{ .Values.kafka.deploy.replicaCount }}
+ podManagementPolicy: Parallel
+ selector:
+ matchLabels:
+ {{- include "aisoc.selectorLabels" . | nindent 6 }}
+ app.kubernetes.io/component: kafka
+ template:
+ metadata:
+ labels:
+ {{- include "aisoc.selectorLabels" . | nindent 8 }}
+ app.kubernetes.io/component: kafka
+ spec:
+ securityContext:
+ runAsNonRoot: true
+ runAsUser: 1000
+ fsGroup: 1000
+ topologySpreadConstraints:
+ - maxSkew: 1
+ topologyKey: kubernetes.io/hostname
+ whenUnsatisfiable: ScheduleAnyway
+ labelSelector:
+ matchLabels:
+ {{- include "aisoc.selectorLabels" . | nindent 14 }}
+ app.kubernetes.io/component: kafka
+ containers:
+ - name: kafka
+ image: "{{ .Values.kafka.deploy.image.repository }}:{{ .Values.kafka.deploy.image.tag }}"
+ imagePullPolicy: {{ .Values.kafka.deploy.image.pullPolicy }}
+ ports:
+ - name: client
+ containerPort: 9092
+ - name: controller
+ containerPort: 9093
+ command: ["/bin/bash", "-c"]
+ args:
+ - |
+ set -euo pipefail
+ # The ordinal is the only per-pod value, and a StatefulSet does
+ # not expose it as a field ref. Deriving it from the hostname is
+ # the supported way; it is stable across restarts, which is what
+ # makes a node id safe to derive from it at all.
+ ordinal="${HOSTNAME##*-}"
+ export KAFKA_NODE_ID="${ordinal}"
+ export KAFKA_ADVERTISED_LISTENERS="PLAINTEXT://${HOSTNAME}.${HEADLESS_SERVICE}.${POD_NAMESPACE}.svc.cluster.local:9092"
+ exec /etc/kafka/docker/run
+ env:
+ - name: POD_NAMESPACE
+ valueFrom:
+ fieldRef:
+ fieldPath: metadata.namespace
+ - name: HEADLESS_SERVICE
+ value: {{ include "aisoc.fullname" . }}-kafka-headless
+ - name: CLUSTER_ID
+ value: {{ .Values.kafka.deploy.clusterId | quote }}
+ - name: KAFKA_PROCESS_ROLES
+ value: "broker,controller"
+ - name: KAFKA_CONTROLLER_QUORUM_VOTERS
+ value: {{ include "aisoc.kafkaQuorumVoters" . | quote }}
+ - name: KAFKA_LISTENERS
+ value: "PLAINTEXT://:9092,CONTROLLER://:9093"
+ - name: KAFKA_LISTENER_SECURITY_PROTOCOL_MAP
+ value: "CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT"
+ - name: KAFKA_CONTROLLER_LISTENER_NAMES
+ value: "CONTROLLER"
+ - name: KAFKA_INTER_BROKER_LISTENER_NAME
+ value: "PLAINTEXT"
+ - name: KAFKA_LOG_DIRS
+ value: "/var/lib/kafka/data"
+ # Durability. A write is acknowledged when two of the three
+ # brokers hold it, so one broker can be lost without loss and
+ # without blocking producers.
+ - name: KAFKA_DEFAULT_REPLICATION_FACTOR
+ value: {{ .Values.kafka.deploy.replicationFactor | quote }}
+ - name: KAFKA_MIN_INSYNC_REPLICAS
+ value: {{ .Values.kafka.deploy.minInsyncReplicas | quote }}
+ - name: KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR
+ value: {{ .Values.kafka.deploy.replicationFactor | quote }}
+ - name: KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR
+ value: {{ .Values.kafka.deploy.replicationFactor | quote }}
+ - name: KAFKA_TRANSACTION_STATE_LOG_MIN_ISR
+ value: {{ .Values.kafka.deploy.minInsyncReplicas | quote }}
+ # Auto-created topics get more than one partition so multiple
+ # fusion replicas can consume in parallel. A single-partition
+ # topic pins the whole consumer group to one replica, which makes
+ # "multi-replica fusion" a claim with nothing behind it.
+ - name: KAFKA_NUM_PARTITIONS
+ value: {{ .Values.kafka.deploy.numPartitions | quote }}
+ - name: KAFKA_AUTO_CREATE_TOPICS_ENABLE
+ value: "true"
+ - name: KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS
+ value: "0"
+ {{- range $k, $v := .Values.kafka.deploy.extraEnv }}
+ - name: {{ $k }}
+ value: {{ $v | quote }}
+ {{- end }}
+ readinessProbe:
+ exec:
+ command:
+ - /bin/bash
+ - -c
+ - /opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092 >/dev/null 2>&1
+ initialDelaySeconds: 20
+ periodSeconds: 10
+ timeoutSeconds: 10
+ failureThreshold: 12
+ livenessProbe:
+ tcpSocket:
+ port: controller
+ initialDelaySeconds: 30
+ periodSeconds: 20
+ failureThreshold: 6
+ resources:
+ {{- toYaml .Values.kafka.deploy.resources | nindent 12 }}
+ securityContext:
+ allowPrivilegeEscalation: false
+ capabilities:
+ drop:
+ - ALL
+ volumeMounts:
+ - name: data
+ mountPath: /var/lib/kafka/data
+ terminationGracePeriodSeconds: 60
+ {{- if not .Values.kafka.deploy.persistence.enabled }}
+ volumes:
+ - name: data
+ emptyDir: {}
+ {{- end }}
+ {{- if .Values.kafka.deploy.persistence.enabled }}
+ volumeClaimTemplates:
+ - metadata:
+ name: data
+ spec:
+ accessModes: ["ReadWriteOnce"]
+ {{- with .Values.kafka.deploy.persistence.storageClass }}
+ storageClassName: {{ . | quote }}
+ {{- end }}
+ resources:
+ requests:
+ storage: {{ .Values.kafka.deploy.persistence.size }}
+ {{- else }}
+ # emptyDir means a restarted broker starts empty. Acceptable only for a
+ # throwaway cluster; with replication factor 3 the partition is re-fetched
+ # from its peers, and with one broker it is data loss.
+ {{- end }}
+{{- end }}
diff --git a/infra/helm/aisoc/templates/kafka-topics-job.yaml b/infra/helm/aisoc/templates/kafka-topics-job.yaml
new file mode 100644
index 000000000..018ffb4af
--- /dev/null
+++ b/infra/helm/aisoc/templates/kafka-topics-job.yaml
@@ -0,0 +1,85 @@
+{{- if and .Values.kafka.deploy.enabled .Values.kafka.deploy.createTopics.enabled }}
+{{- /*
+ Create the spine's topics before anything publishes to them.
+
+ Auto-creation is on, and it is not enough. The first POST to
+ /v1/ingest/batch on a fresh install is answered
+ `{"error":"failed to publish events"}` with
+ `Unknown Topic Or Partition` in the ingest log: the metadata request
+ triggers creation and the produce that triggered it still fails. A retry
+ succeeds, so the symptom is one lost batch at install time and nothing
+ afterwards, which is exactly the kind of loss nobody traces.
+
+ Pre-creating also pins partitions and replication factor rather than
+ inheriting the broker defaults. An auto-created topic takes whatever
+ KAFKA_NUM_PARTITIONS happened to be when the broker booted, so a topic
+ created during a misconfigured window keeps one partition forever and
+ quietly caps fusion at one consuming replica.
+*/}}
+apiVersion: batch/v1
+kind: Job
+metadata:
+ name: {{ include "aisoc.fullname" . }}-kafka-topics
+ namespace: {{ .Release.Namespace }}
+ labels:
+ {{- include "aisoc.labels" . | nindent 4 }}
+ app.kubernetes.io/component: kafka-topics
+ annotations:
+ "helm.sh/hook": post-install,post-upgrade
+ "helm.sh/hook-weight": "5"
+ "helm.sh/hook-delete-policy": before-hook-creation
+spec:
+ backoffLimit: 6
+ ttlSecondsAfterFinished: 600
+ template:
+ metadata:
+ labels:
+ {{- include "aisoc.selectorLabels" . | nindent 8 }}
+ app.kubernetes.io/component: kafka-topics
+ spec:
+ restartPolicy: OnFailure
+ securityContext:
+ runAsNonRoot: true
+ runAsUser: 1000
+ containers:
+ - name: topics
+ image: "{{ .Values.kafka.deploy.image.repository }}:{{ .Values.kafka.deploy.image.tag }}"
+ imagePullPolicy: {{ .Values.kafka.deploy.image.pullPolicy }}
+ command: ["/bin/bash", "-c"]
+ args:
+ - |
+ set -euo pipefail
+ bootstrap="{{ include "aisoc.kafkaBootstrap" . }}"
+ # The Job can start before the quorum has elected a controller,
+ # and `kafka-topics.sh --create` against a broker that has not
+ # joined fails in a way that looks like a configuration error.
+ # Wait for the cluster to answer rather than consuming a
+ # backoffLimit attempt on a race.
+ for attempt in $(seq 1 30); do
+ if /opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server "$bootstrap" >/dev/null 2>&1; then
+ break
+ fi
+ echo "waiting for $bootstrap (attempt $attempt)"
+ sleep 5
+ done
+ for topic in {{ join " " .Values.kafka.deploy.createTopics.names }}; do
+ /opt/kafka/bin/kafka-topics.sh --bootstrap-server "$bootstrap" \
+ --create --if-not-exists --topic "$topic" \
+ --partitions {{ .Values.kafka.deploy.numPartitions }} \
+ --replication-factor {{ .Values.kafka.deploy.replicationFactor }}
+ echo "ok: $topic"
+ done
+ /opt/kafka/bin/kafka-topics.sh --bootstrap-server "$bootstrap" --list
+ resources:
+ requests:
+ cpu: 50m
+ memory: 256Mi
+ limits:
+ cpu: 500m
+ memory: 768Mi
+ securityContext:
+ allowPrivilegeEscalation: false
+ capabilities:
+ drop:
+ - ALL
+{{- end }}
diff --git a/infra/helm/aisoc/templates/service.yaml b/infra/helm/aisoc/templates/service.yaml
index 8d4202768..9c69e9e56 100644
--- a/infra/helm/aisoc/templates/service.yaml
+++ b/infra/helm/aisoc/templates/service.yaml
@@ -15,6 +15,9 @@ spec:
targetPort: http
protocol: TCP
name: http
+ {{- if and $svc.service.nodePort (eq ($svc.service.type | default "ClusterIP") "NodePort") }}
+ nodePort: {{ $svc.service.nodePort }}
+ {{- end }}
{{- if $svc.metricsPort }}
- port: {{ $svc.metricsPort }}
targetPort: metrics
diff --git a/infra/helm/aisoc/templates/ueba-deployment.yaml b/infra/helm/aisoc/templates/ueba-deployment.yaml
index a8276103d..4bb0aa04b 100644
--- a/infra/helm/aisoc/templates/ueba-deployment.yaml
+++ b/infra/helm/aisoc/templates/ueba-deployment.yaml
@@ -1,3 +1,13 @@
+{{- /*
+ `ueba.enabled` had no reader. honeytokens-deployment.yaml and
+ purple-team-deployment.yaml each gate on their own flag; this file did not,
+ so `--set ueba.enabled=false` rendered the Deployment anyway. On a cluster
+ without the UEBA image that is two pods in CreateContainerConfigError for a
+ subsystem the operator switched off, and the switch reads as broken rather
+ than as absent. Same shape as the AISOC_DISABLE_OPENSEARCH setting that
+ nothing read: a control wired to nothing is worse than no control.
+*/}}
+{{- if .Values.ueba.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -31,7 +41,7 @@ spec:
name: {{ include "aisoc.fullname" . }}-secrets
key: database-url
- name: UEBA_KAFKA_BOOTSTRAP_SERVERS
- value: {{ .Values.kafka.bootstrapServers | default "kafka:9092" | quote }}
+ value: {{ include "aisoc.kafkaBootstrap" . | quote }}
- name: UEBA_OTEL_ENDPOINT
value: {{ .Values.otel.endpoint | default "http://otel-collector:4317" | quote }}
livenessProbe:
@@ -95,3 +105,4 @@ spec:
matchLabels:
{{- include "aisoc.selectorLabels" . | nindent 6 }}
app.kubernetes.io/component: ueba
+{{- end }}
diff --git a/infra/helm/aisoc/values-ha.yaml b/infra/helm/aisoc/values-ha.yaml
new file mode 100644
index 000000000..726e8c90e
--- /dev/null
+++ b/infra/helm/aisoc/values-ha.yaml
@@ -0,0 +1,127 @@
+# Reference high-availability deployment.
+#
+# helm install aisoc infra/helm/aisoc -n aisoc \
+# -f infra/helm/aisoc/values-ha.yaml
+#
+# What "HA" means here, precisely: losing one node, or one pod of any
+# component, costs neither availability nor data. It does not mean
+# multi-region, and it does not mean zero-downtime schema migrations.
+#
+# THE TWO STATEFUL THINGS THIS FILE DOES NOT MAKE HIGHLY AVAILABLE
+# ----------------------------------------------------------------
+# PostgreSQL and ClickHouse are left external on purpose. Replicated Postgres
+# with automated failover, and a sharded replicated ClickHouse, are each a
+# full operational discipline, and a chart that ships a single-pod database
+# under a file called values-ha.yaml would be claiming something it does not
+# do. Point the release at a managed service; the options and the trade-offs
+# are in apps/docs/docs/operations/ha-deployment.md.
+#
+# The chart consumes:
+# database-url runtime DSN, as the aisoc_app role
+# database-migration-url owner DSN, used by the migration job and nothing else
+# redis-url
+# from the `<release>-secrets` Secret. The chart ships no Secret template, so
+# creating it is an operator step. See the note above `postgresql:` in
+# values.yaml for why the two DSNs are different roles, and why running the
+# services as the owner silently disables every row-level-security policy.
+
+global:
+ environment: production
+ logLevel: info
+
+# Three brokers, replication factor 3, min.insync.replicas 2. A write is
+# acknowledged once two brokers hold it, so one broker can be lost with
+# neither data loss nor a write stall. Swap to a managed broker by setting
+# kafka.deploy.enabled=false and kafka.bootstrapServers.
+kafka:
+ deploy:
+ enabled: true
+ replicaCount: 3
+ replicationFactor: 3
+ minInsyncReplicas: 2
+ # One partition per fusion replica, so more than one replica can actually
+ # consume. A single-partition topic pins the whole consumer group to one
+ # pod and makes multi-replica fusion decorative.
+ numPartitions: 3
+ persistence:
+ enabled: true
+ size: 50Gi
+
+# Bundled single-pod datastores stay off. See the header.
+postgresql:
+ enabled: false
+redis:
+ enabled: false
+
+services:
+ api:
+ replicaCount: 3
+ pdb:
+ enabled: true
+ minAvailable: 2
+ hpa:
+ enabled: true
+ minReplicas: 3
+ maxReplicas: 12
+
+ # Ingest is the front door and the cheapest thing to scale, so it carries
+ # the most headroom: a burst that ingest cannot accept is data the platform
+ # never sees, which is not recoverable later.
+ ingest:
+ replicaCount: 3
+ pdb:
+ enabled: true
+ minAvailable: 2
+ hpa:
+ enabled: true
+ minReplicas: 3
+ maxReplicas: 24
+
+ # Fusion replicas are Kafka consumers in one group, so the ceiling is the
+ # partition count, not the HPA's maxReplicas: a fourth replica against three
+ # partitions idles. Raise kafka.deploy.numPartitions before raising this.
+ alert-fusion:
+ replicaCount: 3
+ pdb:
+ enabled: true
+ minAvailable: 2
+ hpa:
+ enabled: true
+ minReplicas: 3
+ maxReplicas: 3
+
+ agents:
+ replicaCount: 2
+ pdb:
+ enabled: true
+ minAvailable: 1
+ hpa:
+ enabled: true
+ minReplicas: 2
+ maxReplicas: 6
+
+ web:
+ replicaCount: 3
+ pdb:
+ enabled: true
+ minAvailable: 2
+
+ realtime:
+ replicaCount: 3
+ pdb:
+ enabled: true
+ minAvailable: 2
+
+ enrichment:
+ replicaCount: 2
+ pdb:
+ enabled: true
+ minAvailable: 1
+
+# Egress default-deny. Off in the chart's own defaults because a CNI that
+# does not enforce NetworkPolicy ignores the object silently, and a control
+# that is silently ignored reads as protection while providing none. Check
+# your CNI, then set the CIDRs your vendor APIs and LLM endpoint live behind.
+networkPolicy:
+ enabled: false
+ allowedEgressCIDRs: []
diff --git a/infra/helm/aisoc/values.yaml b/infra/helm/aisoc/values.yaml
index da524c62b..7b687804c 100644
--- a/infra/helm/aisoc/values.yaml
+++ b/infra/helm/aisoc/values.yaml
@@ -31,6 +31,7 @@ services:
containerPort: 8000
metricsPort: 9090
healthCheckPath: /health
+ readinessPath: /readyz
service:
type: ClusterIP
port: 80
@@ -62,6 +63,8 @@ services:
replicaCount: 3
containerPort: 8001
healthCheckPath: /health
+ readinessPath: /readyz
+ waitForKafka: true
service:
type: ClusterIP
port: 80
@@ -124,6 +127,8 @@ services:
replicaCount: 2
containerPort: 8003
healthCheckPath: /health
+ readinessPath: /readyz
+ waitForKafka: true
service:
type: ClusterIP
port: 80
@@ -155,6 +160,8 @@ services:
replicaCount: 2
containerPort: 8004
healthCheckPath: /health
+ readinessPath: /readyz
+ waitForKafka: true
service:
type: ClusterIP
port: 80
@@ -217,6 +224,8 @@ services:
replicaCount: 2
containerPort: 4000
healthCheckPath: /health
+ readinessPath: /readyz
+ waitForKafka: true
service:
type: ClusterIP
port: 80
@@ -341,9 +350,74 @@ purpleTeam:
cpu: 500m
memory: 1Gi
-# Referenced by ueba-deployment.yaml; also absent until now.
+# ─── Kafka ────────────────────────────────────────────────────────────────────
+#
+# `bootstrapServers` is the address of a broker the chart does NOT run. It is
+# the production shape: a managed broker (MSK, Confluent Cloud, Redpanda
+# Cloud) outlives any one release and is not something a SOC should be
+# operating by accident.
+#
+# `deploy` runs brokers inside the release instead. It is off by default
+# because a default install that silently starts a stateful quorum is the
+# wrong surprise, and because a single-replica broker with no persistence is
+# worse than none. Turn it on with values-ha.yaml, which sets three replicas,
+# replication factor 3 and min.insync.replicas 2, the settings that make
+# losing a broker survivable.
kafka:
bootstrapServers: "kafka:9092"
+ deploy:
+ enabled: false
+ replicaCount: 3
+ # Pinned rather than floating: a broker is the one component in this
+ # chart where the version is the on-disk format.
+ image:
+ repository: apache/kafka
+ tag: "3.9.1"
+ pullPolicy: IfNotPresent
+ # KRaft requires a cluster id at format time. Fixed here so a re-install
+ # against existing volumes rejoins its own cluster rather than refusing to
+ # start against log directories formatted for a different one.
+ clusterId: "aisoc-kraft-cluster-0"
+ replicationFactor: 3
+ minInsyncReplicas: 2
+ numPartitions: 3
+ persistence:
+ enabled: true
+ size: 50Gi
+ storageClass: ""
+ resources:
+ requests:
+ cpu: 250m
+ memory: 1Gi
+ limits:
+ cpu: 2000m
+ memory: 3Gi
+ extraEnv: {}
+ # A post-install hook that creates the spine's topics before anything
+ # publishes. Auto-creation alone loses the first batch after an install:
+ # the produce that triggers creation is the one that fails. It also pins
+ # partitions and replication factor instead of inheriting whatever the
+ # broker defaults were at boot.
+ createTopics:
+ enabled: true
+ names:
+ - aisoc.raw_events
+ - aisoc.alerts.fused
+ - aisoc.alerts.raw
+ - ueba.anomalies
+ # An init container on every service that declares `waitForKafka: true`,
+ # holding it back until a broker answers. A consumer whose bootstrap fails
+ # does not retry: the worker task ends, the pod keeps answering /health with
+ # 200, and the spine is silently unconsumed. Ordering is cheaper than
+ # detecting that afterwards.
+ waitForBroker:
+ enabled: true
+ attempts: 60
+ intervalSeconds: 5
+ image:
+ repository: apache/kafka
+ tag: "3.9.1"
+ pullPolicy: IfNotPresent
otel:
endpoint: ""
diff --git a/scripts/chaos/fusion_restart.py b/scripts/chaos/fusion_restart.py
new file mode 100644
index 000000000..48f0355fc
--- /dev/null
+++ b/scripts/chaos/fusion_restart.py
@@ -0,0 +1,400 @@
+#!/usr/bin/env python3
+"""Chaos test: kill fusion mid-stream, assert no loss and no duplicates.
+
+The claim
+---------
+A fusion replica can be destroyed while events are flowing and every event
+that ingest accepted still becomes exactly one alert row. Not "roughly all of
+them", and not "at least one row each".
+
+Why the assertion is made against Postgres and nothing else
+-----------------------------------------------------------
+It would be easier to ask the replacement pod whether it thinks it recovered,
+or to read a counter out of the process. Both would be a service grading its
+own homework, and this repository has the scar: a UEBA consumer whose handler
+raised had no ``except`` at all, so the ``async for`` exited, the ``finally``
+stopped the consumer, and the container sat at ``Running`` with restarts 0 and
+``/health`` answering 200, permanently, with the exception never logged. Every
+in-process signal said healthy.
+
+So the only evidence this test accepts is rows in the alert store. The producer
+stamps a sequence number into every event's title; after the run, each accepted
+sequence number must appear in ``alerts`` exactly once. A missing one is loss.
+A repeated one is a duplicate. Both are counted and both fail.
+
+What makes the property true, so a failure is diagnosable
+---------------------------------------------------------
+Two independent mechanisms, and the test is really asking whether they still
+hold together:
+
+* ``services/fusion/app/workers/consumer.py`` runs with
+ ``enable_auto_commit=False`` and commits only after a message is fully
+ processed. A kill between processing and commit re-delivers on restart,
+ which is at-least-once: it cannot lose, and it can duplicate.
+* ``services/fusion/app/services/alert_sink.py`` inserts under
+ ``WHERE NOT EXISTS (… tenant_id = $2 AND dedup_hash = $11)``, so the
+ re-delivery does not become a second row. That converts at-least-once into
+ effectively-once at the store.
+
+Remove either and this test fails in a distinguishable direction: losing the
+commit discipline shows up as missing rows, losing the dedup guard as
+duplicates.
+
+Usage
+-----
+::
+
+ # kubernetes (the shape the plan names: kill a pod)
+ python3 scripts/chaos/fusion_restart.py --target kubernetes \\
+ --namespace aisoc --token "$AISOC_INGEST_TOKEN" \\
+ --ingest-url http://127.0.0.1:30081/v1/ingest/batch
+
+ # docker compose (kill the container)
+ python3 scripts/chaos/fusion_restart.py --target compose \\
+ --token "$AISOC_INGEST_TOKEN"
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+import time
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "perf"))
+
+from gate_toolkit import repo_root, self_test_main # noqa: E402
+from load_harness import ( # noqa: E402
+ MARKER_PREFIX,
+ Target,
+ collect_alerts,
+ compose_target,
+ kubernetes_target,
+)
+
+_FUSION_K8S_SELECTOR = "app.kubernetes.io/component=alert-fusion"
+
+
+@dataclass
+class Verdict:
+ """What the alert store says happened, independent of what any pod says."""
+
+ accepted: int
+ alert_rows: int
+ distinct_seqs: int
+ missing: list[int]
+ duplicated: list[int]
+
+ @property
+ def ok(self) -> bool:
+ return self.accepted > 0 and not self.missing and not self.duplicated
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "accepted_events": self.accepted,
+ "alert_rows": self.alert_rows,
+ "distinct_events_alerted": self.distinct_seqs,
+ "missing_count": len(self.missing),
+ "duplicate_count": len(self.duplicated),
+ # Bounded so a total failure does not write a hundred-thousand-line
+ # report, but never summarised to a bare count: the ids are what
+ # makes a failure reproducible.
+ "missing_sample": self.missing[:25],
+ "duplicated_sample": self.duplicated[:25],
+ "verdict": "no loss, no duplicates" if self.ok else "FAILED",
+ }
+
+
+def grade(accepted: int, seq_counts: dict[int, int]) -> Verdict:
+ """Compare what ingest accepted against what the alert store holds.
+
+ Sequence numbers are contiguous from 0 by construction (the producer hands
+ them out from one atomic counter), so "which ones are missing" is a set
+ difference rather than a guess.
+ """
+ expected = range(accepted)
+ missing = sorted(seq for seq in expected if seq not in seq_counts)
+ duplicated = sorted(seq for seq, count in seq_counts.items() if count > 1)
+ return Verdict(
+ accepted=accepted,
+ alert_rows=sum(seq_counts.values()),
+ distinct_seqs=len(seq_counts),
+ missing=missing,
+ duplicated=duplicated,
+ )
+
+
+def fusion_victims(target: Target, namespace: str) -> list[str]:
+ if target.name == "kubernetes":
+ out = subprocess.run( # noqa: S603
+ [
+ "kubectl",
+ "-n",
+ namespace,
+ "get",
+ "pods",
+ "-l",
+ _FUSION_K8S_SELECTOR,
+ "--field-selector=status.phase=Running",
+ "-o",
+ "jsonpath={.items[*].metadata.name}",
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return out.stdout.split()
+ out = subprocess.run( # noqa: S603
+ ["docker", "ps", "--filter", "name=aisoc-fusion", "--format", "{{.Names}}"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return [name for name in out.stdout.split() if name]
+
+
+def kill_fusion(target: Target, namespace: str, victim: str) -> tuple[bool, str]:
+ """Destroy the replica without letting it shut down cleanly.
+
+ ``--grace-period=0 --force`` and ``docker kill -s KILL`` are both
+ deliberate: a graceful stop runs fusion's ``stop()``, which stops the
+ consumer in an orderly way and would test the shutdown path rather than
+ the crash path. The failure worth proving survivable is the one where the
+ process never gets to run any code at all.
+ """
+ if target.name == "kubernetes":
+ argv = ["kubectl", "-n", namespace, "delete", "pod", victim, "--grace-period=0", "--force", "--wait=false"]
+ else:
+ argv = ["docker", "kill", "-s", "KILL", victim]
+ done = subprocess.run(argv, capture_output=True, text=True, check=False) # noqa: S603
+ return done.returncode == 0, (done.stderr or done.stdout).strip()[:300]
+
+
+def count_marked(target: Target, run_id: str) -> int:
+ raw = target.sql(f"select count(*) from alerts where title like '{MARKER_PREFIX} {run_id} %'")
+ return int(raw or 0)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--target", choices=("compose", "kubernetes"), default="kubernetes")
+ parser.add_argument("--namespace", default="aisoc")
+ parser.add_argument("--events", type=int, default=6000)
+ parser.add_argument("--target-eps", type=int, default=100, help="paced so the kill lands mid-stream, not after it")
+ parser.add_argument("--workers", type=int, default=4)
+ parser.add_argument("--batch", type=int, default=20)
+ parser.add_argument("--kill-at", type=float, default=0.4, help="fraction of the push elapsed before the kill")
+ parser.add_argument("--token", default=os.environ.get("AISOC_INGEST_TOKEN", ""))
+ parser.add_argument("--tenant", default=os.environ.get("AISOC_TENANT_ID", "00000000-0000-0000-0000-000000000001"))
+ parser.add_argument("--ingest-url", default=os.environ.get("AISOC_INGEST_URL", "http://localhost:8081/v1/ingest/batch"))
+ parser.add_argument("--compose-file", action="append", default=[])
+ parser.add_argument("--postgres-ref", default="statefulset/postgres")
+ parser.add_argument("--kafka-ref", default="statefulset/aisoc-kafka")
+ parser.add_argument("--producer-bin", default=os.environ.get("AISOC_PRODUCER_BIN", ""))
+ parser.add_argument("--drain-timeout", type=int, default=420)
+ parser.add_argument("--out", type=Path)
+ args = parser.parse_args(argv)
+
+ root = repo_root()
+ if not (root / "services" / "fusion").is_dir() or not (root / "services" / "demo-producer").is_dir():
+ print(
+ "fusion_restart: services/fusion and services/demo-producer are not in this tree; "
+ "there is nothing to kill and nothing to drive it with",
+ file=sys.stderr,
+ )
+ return 2
+ if not args.token:
+ print("fusion_restart: no ingest credential. Pass --token or set AISOC_INGEST_TOKEN (`make ingest-token`).", file=sys.stderr)
+ return 2
+
+ target = (
+ compose_target(root, args.compose_file or ["docker-compose.yml"], args.ingest_url)
+ if args.target == "compose"
+ else kubernetes_target(args.namespace, "aisoc", args.ingest_url, args.postgres_ref, args.kafka_ref)
+ )
+
+ before = fusion_victims(target, args.namespace)
+ if len(before) < 2:
+ print(
+ f"fusion_restart: found {len(before)} running fusion replica(s): {before or 'none'}. "
+ "This test needs at least two, because with one there is nothing for the surviving "
+ "consumer to take over and the result would only measure restart time.",
+ file=sys.stderr,
+ )
+ return 2
+
+ run_id = f"c{int(time.time()) % 100000000:08d}"
+ summary_path = Path(os.environ.get("TMPDIR", "/tmp")) / f"aisoc-chaos-{run_id}.json"
+ producer = [args.producer_bin] if args.producer_bin else ["go", "run", "./services/demo-producer"]
+ producer += [
+ "--load",
+ "--ingest-url",
+ args.ingest_url,
+ "--token",
+ args.token,
+ "--tenant",
+ args.tenant,
+ "--total",
+ str(args.events),
+ "--workers",
+ str(args.workers),
+ "--batch",
+ str(args.batch),
+ "--target-eps",
+ str(args.target_eps),
+ "--run-id",
+ run_id,
+ "--summary",
+ str(summary_path),
+ ]
+
+ expected_seconds = args.events / max(1, args.target_eps)
+ print(
+ f"chaos: run={run_id} events={args.events} paced at {args.target_eps}/s "
+ f"(about {expected_seconds:.0f}s of stream); killing a replica at {args.kill_at:.0%}"
+ )
+
+ started = time.time()
+ proc = subprocess.Popen(producer, cwd=root, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True) # noqa: S603
+
+ # The kill has to land while events are still arriving. Waiting on the
+ # clock alone would fire early on a stack that never started, so the
+ # alert store is checked first: rows for this run mean the stream is live.
+ deadline = started + expected_seconds * args.kill_at
+ while time.time() < deadline:
+ time.sleep(1)
+ if proc.poll() is not None:
+ break
+ in_flight = count_marked(target, run_id)
+ victim = before[0]
+ killed_ok, detail = kill_fusion(target, args.namespace, victim)
+ killed_at = time.time()
+ print(
+ f"chaos: killed {victim} at t+{killed_at - started:.0f}s with {in_flight:,} alerts already stored "
+ f"({'ok' if killed_ok else 'FAILED: ' + detail})"
+ )
+ if not killed_ok:
+ proc.kill()
+ return 2
+ if in_flight == 0:
+ print(
+ "chaos: no alerts had been stored when the kill landed, so the replica was destroyed "
+ "before the stream reached it. That tests nothing; re-run with a lower --target-eps "
+ "or a later --kill-at.",
+ file=sys.stderr,
+ )
+ proc.kill()
+ return 2
+
+ _, producer_err = proc.communicate(timeout=max(300, expected_seconds * 4))
+ if proc.returncode != 0:
+ print(f"chaos: producer failed ({proc.returncode}): {producer_err[-400:]}", file=sys.stderr)
+ return 2
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
+ accepted = int(summary["accepted_events"])
+
+ drain_started = time.time()
+ stable_reads = 0
+ last = -1
+ while time.time() - drain_started < args.drain_timeout:
+ count = count_marked(target, run_id)
+ if count >= accepted:
+ break
+ # Three identical reads is the stopping rule when rows are still
+ # missing: one could be the gap between two batches.
+ stable_reads = stable_reads + 1 if count == last else 0
+ if stable_reads >= 3:
+ break
+ last = count
+ time.sleep(5)
+
+ seq_counts: dict[int, int] = {}
+ for row in collect_alerts(target, run_id):
+ seq_counts[row.seq] = seq_counts.get(row.seq, 0) + 1
+ verdict = grade(accepted, seq_counts)
+
+ after = fusion_victims(target, args.namespace)
+ replaced = args.target == "compose" or (victim not in after and len(after) >= len(before))
+
+ report = {
+ "schema": "aisoc.chaos_fusion_restart/v1",
+ "measured_at": datetime.now(UTC).isoformat(timespec="seconds"),
+ "deployment": target.name,
+ "run_id": run_id,
+ "replica_killed": victim,
+ "replicas_before": before,
+ "replicas_after": after,
+ "replica_replaced": replaced,
+ "killed_at_offset_seconds": round(killed_at - started, 1),
+ "alerts_stored_when_killed": in_flight,
+ "drain_seconds": round(time.time() - drain_started, 1),
+ **verdict.as_dict(),
+ }
+ if args.out:
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps(report, indent=2))
+
+ if not verdict.ok:
+ print(
+ f"\nFAIL: {len(verdict.missing)} event(s) produced no alert and {len(verdict.duplicated)} produced more than one.",
+ file=sys.stderr,
+ )
+ return 1
+ if not replaced:
+ print(
+ "\nFAIL: the killed replica was not replaced, so the run survived by running at reduced capacity rather than by recovering.",
+ file=sys.stderr,
+ )
+ return 1
+ print(
+ f"\nPASS: {accepted:,} accepted events produced {accepted:,} alert rows across a replica kill "
+ f"at t+{report['killed_at_offset_seconds']}s. No loss, no duplicates."
+ )
+ return 0
+
+
+def _self_test() -> int:
+ """Prove the verdict fails in both directions it is supposed to catch."""
+ checks = [
+ (
+ "a clean run passes",
+ grade(5, {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}).ok,
+ ),
+ (
+ "a lost event fails and is named, rather than being absorbed into a rate",
+ (lambda v: not v.ok and v.missing == [2] and v.as_dict()["missing_sample"] == [2])(grade(5, {0: 1, 1: 1, 3: 1, 4: 1})),
+ ),
+ (
+ "a duplicated event fails even though every event is present",
+ (lambda v: not v.ok and v.duplicated == [1] and not v.missing)(grade(5, {0: 1, 1: 2, 2: 1, 3: 1, 4: 1})),
+ ),
+ (
+ "a loss and a duplicate that cancel out in the row count still fail",
+ (lambda v: not v.ok and v.alert_rows == 5 and v.missing == [4] and v.duplicated == [1])(grade(5, {0: 1, 1: 2, 2: 1, 3: 1})),
+ ),
+ (
+ "a run where nothing was accepted is not a pass",
+ not grade(0, {}).ok,
+ ),
+ ]
+ ok = True
+ for description, passed in checks:
+ ok &= passed
+ print(f" {'PASS' if passed else 'FAIL'} {description}")
+ print()
+ print("fusion_restart.py: self-test " + ("OK" if ok else "FAILED"))
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ if "--self-test" in sys.argv[1:]:
+ sys.exit(_self_test() or self_test_main("chaos/fusion_restart.py", []))
+ sys.exit(main())
diff --git a/scripts/check_comment_paths.py b/scripts/check_comment_paths.py
index 9f442eb5f..15583c6e3 100644
--- a/scripts/check_comment_paths.py
+++ b/scripts/check_comment_paths.py
@@ -175,6 +175,13 @@ URL_PREFIX_RE = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*://\S*|[A-Za-z0-9-]+\.[A-
#: 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] = {
+ ("scripts/perf/load_harness.py", "scripts/load_harness.py"): (
+ "Prose asserting the file's absence. The comment explains why the self-test probe is "
+ "passed 'perf/load_harness.py' rather than a basename: a basename would have resolved to "
+ "scripts/load_harness.py, which does not exist, and a missing file exits non-zero so the "
+ "refusal would have passed while proving nothing. Making this path resolve would recreate "
+ "the trap the comment exists to warn about."
+ ),
(".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."
diff --git a/scripts/check_perf_results.py b/scripts/check_perf_results.py
new file mode 100644
index 000000000..20f5361dc
--- /dev/null
+++ b/scripts/check_perf_results.py
@@ -0,0 +1,254 @@
+#!/usr/bin/env python3
+"""Every published performance figure carries its hardware, its date, and the words that stop it reading as an SLO.
+
+What this gate is for
+---------------------
+A throughput number is only interpretable next to the machine it came off and
+the day it was taken. Published alone it becomes a promise, and the first
+person to quote it in a sales conversation turns a laptop measurement into a
+service-level objective nobody agreed to.
+
+So a committed result under ``docs/perf/results/`` must carry:
+
+* ``measured_at`` an ISO-8601 date;
+* ``hardware`` with enough to identify the machine;
+* ``not_a_production_slo`` literally ``true``;
+* ``slo_disclaimer`` prose a reader will actually see.
+
+And the prose page that presents them (``apps/docs/docs/operations/performance.md``)
+must name the same dates the files carry and say, above the first table, that
+these are not an SLO. A results directory that drifts from its own page is how
+a figure outlives the conditions that produced it.
+
+The rule about zero
+-------------------
+``scripts/perf/load_harness.py`` emits each metric as measured-with-a-value or
+unmeasured-with-a-reason and never both. This gate enforces the half that
+matters at rest: an unmeasured metric must carry no ``value`` key, so no
+renderer downstream can turn an absence into ``0.00``. The inverse is checked
+too, because a measured zero is real information (zero dead letters, zero
+consumer lag) and must survive.
+
+Usage::
+
+ python3 scripts/check_perf_results.py # verdict
+ python3 scripts/check_perf_results.py --self-test
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import repo_root, self_test_main # noqa: E402
+
+RESULTS_DIR = Path("docs/perf/results")
+PAGE = Path("apps/docs/docs/operations/performance.md")
+
+#: Present in every result, whatever produced it.
+_REQUIRED_TOP = ("schema", "measured_at")
+
+#: Enough to answer "what machine was this?". Not a fixed list, because a CI
+#: runner and a laptop describe themselves differently; at least one of these
+#: has to be there, and the cpu-count-style fields alone are not enough.
+_HARDWARE_IDENTIFIERS = ("cpu", "container_runtime", "ci_runner")
+
+_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}")
+
+#: The phrase the page has to carry. Matched case-insensitively on the words
+#: rather than on an exact sentence, so the prose can be rewritten without
+#: the gate becoming a spelling test.
+_SLO_PHRASE = re.compile(r"not\s+a\s+(production\s+)?service[- ]level objective|not\s+a\s+production\s+slo", re.I)
+
+
+def _findings_for(path: Path, blob: dict) -> list[str]:
+ findings: list[str] = []
+ name = path.name
+
+ for key in _REQUIRED_TOP:
+ if not blob.get(key):
+ findings.append(f"{name}: no {key}")
+ measured_at = str(blob.get("measured_at", ""))
+ if measured_at and not _DATE_RE.match(measured_at):
+ findings.append(f"{name}: measured_at {measured_at!r} does not begin with an ISO date")
+ if measured_at[:10] and not name.startswith(measured_at[:10]):
+ findings.append(f"{name}: filename does not begin with its own measurement date {measured_at[:10]}")
+
+ schema = str(blob.get("schema", ""))
+ # The chaos result is a pass/fail statement about correctness, not a
+ # performance figure, so it is not required to carry the SLO apparatus.
+ # It is still required to say when it was taken and what it found.
+ is_perf = schema.startswith("aisoc.load_harness")
+
+ if is_perf:
+ hardware = blob.get("hardware") or {}
+ if not isinstance(hardware, dict) or not hardware:
+ findings.append(f"{name}: no hardware block, so the numbers describe no machine")
+ elif not any(hardware.get(k) for k in _HARDWARE_IDENTIFIERS):
+ findings.append(
+ f"{name}: hardware block names none of {', '.join(_HARDWARE_IDENTIFIERS)}, so a reader cannot tell what produced the figure"
+ )
+ if blob.get("not_a_production_slo") is not True:
+ findings.append(f"{name}: not_a_production_slo is not true")
+ if not str(blob.get("slo_disclaimer", "")).strip():
+ findings.append(f"{name}: no slo_disclaimer prose")
+
+ metrics = blob.get("metrics")
+ if not isinstance(metrics, dict) or not metrics:
+ findings.append(f"{name}: no metrics")
+ else:
+ for metric, body in metrics.items():
+ if not isinstance(body, dict) or "measured" not in body:
+ findings.append(f"{name}: metric {metric} does not say whether it was measured")
+ continue
+ if body["measured"] and "value" not in body:
+ findings.append(f"{name}: metric {metric} claims measured with no value")
+ if not body["measured"]:
+ if "value" in body:
+ findings.append(
+ f"{name}: metric {metric} was not measured but carries a value, "
+ "which is how an absence gets rendered as a number"
+ )
+ if not str(body.get("reason", "")).strip():
+ findings.append(f"{name}: metric {metric} was not measured and says nothing about why")
+ elif schema.startswith("aisoc.chaos"):
+ if blob.get("verdict") is None:
+ findings.append(f"{name}: chaos result with no verdict")
+ else:
+ findings.append(f"{name}: unrecognised schema {schema!r}")
+ return findings
+
+
+def check(root: Path) -> tuple[int, list[str]]:
+ results_dir = root / RESULTS_DIR
+ findings: list[str] = []
+
+ if not results_dir.is_dir():
+ return 0, [f"{RESULTS_DIR} does not exist, so there are no published figures to stand behind"]
+
+ files = sorted(results_dir.glob("*.json"))
+ if not files:
+ return 0, [
+ f"{RESULTS_DIR} holds no results; a performance claim with no measurement behind it is the thing this gate exists to stop"
+ ]
+
+ dates: set[str] = set()
+ for path in files:
+ try:
+ blob = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ findings.append(f"{path.name}: unreadable ({exc})")
+ continue
+ findings.extend(_findings_for(path, blob))
+ measured_at = str(blob.get("measured_at", ""))[:10]
+ if measured_at:
+ dates.add(measured_at)
+
+ page = root / PAGE
+ if not page.is_file():
+ findings.append(f"{PAGE} does not exist, so the results are published as JSON nobody reads")
+ else:
+ text = page.read_text(encoding="utf-8")
+ if not _SLO_PHRASE.search(text):
+ findings.append(f"{PAGE} does not say these figures are not a service-level objective")
+ for date in sorted(dates):
+ if date not in text:
+ findings.append(
+ f"{PAGE} does not mention {date}, which a committed result carries. "
+ "A page that has drifted from the files presents figures under the wrong date"
+ )
+
+ return len(files), findings
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--check", action="store_true", help="accepted for symmetry; this gate always renders a verdict")
+ parser.parse_args(argv)
+
+ root = repo_root()
+ scanned, findings = check(root)
+
+ if findings:
+ print(f"check_perf_results: {len(findings)} finding(s) across {scanned} result file(s)\n")
+ for finding in findings:
+ print(f" FAIL {finding}")
+ return 1
+ print(
+ f"OK: {scanned} published performance result(s), each carrying its hardware, its date "
+ "and the label that stops it being read as an SLO."
+ )
+ return 0
+
+
+def _self_test() -> int:
+ """Inject each violation this gate exists for and require it to be caught."""
+ good = {
+ "schema": "aisoc.load_harness/v1",
+ "measured_at": "2026-09-27T13:45:36+00:00",
+ "hardware": {"cpu": "Apple M5 Max", "container_runtime": "docker 29.5.2"},
+ "not_a_production_slo": True,
+ "slo_disclaimer": "One deployment, this hardware, this date.",
+ "metrics": {
+ "pipeline_eps": {"unit": "events/s", "measured": True, "samples": 10, "value": 176.9},
+ "latency_p99_ms": {"unit": "ms", "measured": False, "samples": 0, "reason": "no alerts landed"},
+ },
+ }
+ path = Path("2026-09-27-example.json")
+ checks = [("a well-formed result passes", not _findings_for(path, good))]
+
+ def breaks(mutate) -> bool:
+ blob = json.loads(json.dumps(good))
+ mutate(blob)
+ return bool(_findings_for(path, blob))
+
+ checks += [
+ ("a result with no hardware block is rejected", breaks(lambda b: b.pop("hardware"))),
+ (
+ "a hardware block that names only a core count is rejected, since it identifies no machine",
+ breaks(lambda b: b.update(hardware={"cpu_count": 8})),
+ ),
+ ("a result with no date is rejected", breaks(lambda b: b.pop("measured_at"))),
+ (
+ "a result whose filename disagrees with its date is rejected",
+ breaks(lambda b: b.update(measured_at="2020-01-01T00:00:00+00:00")),
+ ),
+ ("not_a_production_slo set to false is rejected", breaks(lambda b: b.update(not_a_production_slo=False))),
+ ("a missing disclaimer is rejected", breaks(lambda b: b.update(slo_disclaimer=" "))),
+ (
+ "an unmeasured metric carrying a value is rejected, because that is how an absence becomes a zero",
+ breaks(lambda b: b["metrics"]["latency_p99_ms"].update(value=0.0)),
+ ),
+ (
+ "an unmeasured metric with no reason is rejected",
+ breaks(lambda b: b["metrics"]["latency_p99_ms"].pop("reason")),
+ ),
+ (
+ "a measured metric with no value is rejected",
+ breaks(lambda b: b["metrics"]["pipeline_eps"].pop("value")),
+ ),
+ ]
+
+ # A measured zero must survive: it is a real result, not an absence.
+ zeroed = json.loads(json.dumps(good))
+ zeroed["metrics"]["pipeline_eps"] = {"unit": "events/s", "measured": True, "samples": 10, "value": 0.0}
+ checks.append(("a measured zero is not mistaken for an unmeasured metric", not _findings_for(path, zeroed)))
+
+ ok = True
+ for description, passed in checks:
+ ok &= passed
+ print(f" {'PASS' if passed else 'FAIL'} {description}")
+ print()
+ print("check_perf_results.py: self-test " + ("OK" if ok else "FAILED"))
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ if "--self-test" in sys.argv[1:]:
+ sys.exit(_self_test() or self_test_main("check_perf_results.py", ["--check"]))
+ sys.exit(main())
diff --git a/scripts/perf/load_harness.py b/scripts/perf/load_harness.py
new file mode 100644
index 000000000..91dc8ae1a
--- /dev/null
+++ b/scripts/perf/load_harness.py
@@ -0,0 +1,851 @@
+#!/usr/bin/env python3
+"""End-to-end load harness: ingest -> Kafka -> fusion -> Postgres.
+
+What this measures, and what the existing harness next to it does not
+---------------------------------------------------------------------
+``throughput_harness.py`` times one function, ``promote_normalized_event``,
+in one process. That is the right shape for a regression floor on the CPU-bound
+stage, and it is not production evidence: it never opens a socket, never
+serialises to Kafka, never writes a row, and never competes for a runner's
+page cache with a broker.
+
+This harness drives the deployed stack. It pushes attributable events through
+the real ingest endpoint with the real credential, waits for them to arrive in
+the real ``alerts`` table, and reports:
+
+* **sustained events per second**, twice. ``ingest_accepted_eps`` is what the
+ front door took. ``pipeline_eps`` is how fast alerts actually landed, which
+ is the number that degrades first when fusion falls behind, and the two
+ diverge exactly when the queue is absorbing the difference.
+* **event-to-alert latency** p50/p95/p99, per event rather than averaged over
+ a batch, and corrected for the measured offset between this process's clock
+ and the database's rather than assuming they agree.
+* **consumer lag** on the fusion group, sampled while the run is in flight and
+ again once it has drained. A lag figure taken only at the end says nothing:
+ a drained queue reads zero however far behind it got.
+* **dead-letter rate**, as rows that appeared in ``aisoc_dead_letters``
+ during the window over events attempted.
+* **resource use**, sampled from the container runtime during the run.
+* **delivery**: how many of the accepted events became exactly one alert, how
+ many are missing, and how many produced more than one row.
+
+Two things this deliberately refuses to do
+------------------------------------------
+It never renders a figure it did not measure as ``0``. Every metric is a
+``Measurement`` that is either measured with a value and a sample count, or
+unmeasured with the reason why, and the JSON carries no ``value`` key in the
+second case. A p99 over zero correlated alerts is not "0 ms".
+
+And it never publishes a number without the hardware it was taken on and the
+date. ``scripts/check_perf_results.py`` enforces that on everything committed
+under ``docs/perf/results/``, including the label saying this is not a
+production service-level objective. CI runners are shared, throttled and
+noisy; a floor here fires on a catastrophic regression, not on jitter.
+
+Usage
+-----
+::
+
+ # against a local `make up` stack
+ python3 scripts/perf/load_harness.py \
+ --token "$AISOC_INGEST_TOKEN" --events 20000 --workers 8
+
+ # against a kind/k3d deployment of the Helm chart
+ python3 scripts/perf/load_harness.py --target kubernetes \
+ --namespace aisoc --token "$AISOC_INGEST_TOKEN" --events 5000
+
+ # regression floor, for perf.yml
+ python3 scripts/perf/load_harness.py --token ... --assert-eps-floor 50 \
+ --assert-p95-ceiling-ms 60000
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import platform
+import re
+import shutil
+import statistics
+import subprocess
+import sys
+import time
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from gate_toolkit import repo_root, self_test_main # noqa: E402
+
+#: Must equal ``MarkerPrefix`` in services/demo-producer/main.go. The producer
+#: stamps it into every title; this harness matches alert rows on it. A test
+#: pins the two together, because a silent disagreement would look like a
+#: pipeline that lost every event.
+MARKER_PREFIX = "aisoc-load"
+
+#: ``aisoc-load <run-id> seq=<n> t=<unix-nanoseconds>``
+_TITLE_RE = re.compile(rf"^{re.escape(MARKER_PREFIX)} (?P<run>[A-Za-z0-9_-]+) seq=(?P<seq>\d+) t=(?P<sent>\d+)$")
+
+_FUSION_GROUP = "aisoc-fusion-consumer"
+_DEFAULT_TENANT = "00000000-0000-0000-0000-000000000001"
+
+#: The containers whose CPU and memory are worth publishing beside a
+#: throughput figure. A number without them describes a machine, not a stack.
+_RESOURCE_SERVICES = ("ingest", "fusion", "kafka", "postgres", "api", "agents")
+
+
+# ── measurement ─────────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class Measurement:
+ """A number and what it is over, or the reason there is no number.
+
+ The repository's standing rule is that a figure that was not measured
+ reads "not measured", never ``0``. Encoding that as a type rather than a
+ convention is what stops a formatter rounding an unrun metric into a
+ confident zero: :meth:`as_dict` emits no ``value`` key at all when the
+ measurement did not happen.
+ """
+
+ name: str
+ unit: str
+ value: float | None = None
+ samples: int = 0
+ reason: str | None = None
+
+ @property
+ def measured(self) -> bool:
+ return self.value is not None
+
+ def render(self) -> str:
+ if not self.measured:
+ return f"not measured ({self.reason or 'no reason recorded'})"
+ return f"{self.value:,.2f} {self.unit} (n={self.samples:,})"
+
+ def as_dict(self) -> dict[str, Any]:
+ out: dict[str, Any] = {"unit": self.unit, "measured": self.measured, "samples": self.samples}
+ if self.measured:
+ out["value"] = self.value
+ else:
+ out["reason"] = self.reason or "no reason recorded"
+ return out
+
+
+def measured(name: str, unit: str, value: float, samples: int) -> Measurement:
+ return Measurement(name=name, unit=unit, value=value, samples=samples)
+
+
+def unmeasured(name: str, unit: str, reason: str) -> Measurement:
+ return Measurement(name=name, unit=unit, reason=reason)
+
+
+def percentile(sorted_values: list[float], fraction: float) -> float:
+ """Nearest-rank percentile. Caller sorts; caller guarantees non-empty."""
+ if not sorted_values:
+ raise ValueError("percentile of an empty sample")
+ rank = max(1, min(len(sorted_values), int(round(fraction * len(sorted_values) + 0.5))))
+ return sorted_values[rank - 1]
+
+
+# ── target adapters ─────────────────────────────────────────────────────────
+
+
+@dataclass
+class Target:
+ """How to reach the datastores and the runtime, for one deployment shape.
+
+ ``compose`` and ``kubernetes`` differ only in the command prefixes, so the
+ measurement code below is identical for both. That matters: if the two
+ paths measured differently, publishing a compose number beside a kind
+ number would be comparing two harnesses rather than two deployments.
+ """
+
+ name: str
+ psql: list[str]
+ kafka: list[str]
+ stats: list[str] | None
+ ingest_url: str
+
+ def sql(self, query: str, *, timeout: int = 120) -> str:
+ done = subprocess.run( # noqa: S603 - fixed argv built from operator-supplied prefix
+ [*self.psql, "-tAc", query],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ check=False,
+ )
+ if done.returncode != 0:
+ raise RuntimeError(f"psql failed ({done.returncode}): {(done.stderr or done.stdout).strip()[:400]}")
+ return done.stdout.strip()
+
+ def kafka_lag(self, group: str, *, timeout: int = 60) -> tuple[int | None, str]:
+ """Total lag across the group's partitions, or None and why not."""
+ if not self.kafka:
+ return None, "no kafka command configured for this target"
+ try:
+ done = subprocess.run( # noqa: S603
+ [*self.kafka, "--bootstrap-server", "localhost:9092", "--describe", "--group", group],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return None, f"kafka-consumer-groups did not answer: {exc}"
+ if done.returncode != 0:
+ return None, f"kafka-consumer-groups failed: {(done.stderr or done.stdout).strip()[:200]}"
+ total = 0
+ rows = 0
+ for line in done.stdout.splitlines():
+ fields = line.split()
+ if len(fields) < 6 or fields[0] != group:
+ continue
+ try:
+ total += int(fields[5])
+ except ValueError:
+ continue
+ rows += 1
+ if rows == 0:
+ return None, f"consumer group {group} reported no partitions"
+ return total, ""
+
+
+def compose_target(project_dir: Path, compose_files: list[str], ingest_url: str) -> Target:
+ base = ["docker", "compose"]
+ for spec in compose_files:
+ base += ["-f", spec]
+ return Target(
+ name="docker-compose",
+ psql=[*base, "exec", "-T", "postgres", "psql", "-U", "aisoc", "-d", "aisoc"],
+ kafka=[*base, "exec", "-T", "kafka", "kafka-consumer-groups"],
+ stats=["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"],
+ ingest_url=ingest_url,
+ )
+
+
+def kubernetes_target(namespace: str, release: str, ingest_url: str, postgres_ref: str, kafka_ref: str) -> Target:
+ kubectl = ["kubectl", "-n", namespace]
+ return Target(
+ name="kubernetes",
+ psql=[*kubectl, "exec", "-i", postgres_ref, "--", "psql", "-U", "aisoc", "-d", "aisoc"],
+ kafka=[*kubectl, "exec", "-i", kafka_ref, "--", "/opt/kafka/bin/kafka-consumer-groups.sh"],
+ # `kubectl top` needs metrics-server, which kind does not ship. Absent
+ # is reported as absent rather than as zero usage.
+ stats=[*kubectl, "top", "pods", "--no-headers"],
+ ingest_url=ingest_url,
+ )
+
+
+# ── the run ─────────────────────────────────────────────────────────────────
+
+
+@dataclass
+class ProducerSummary:
+ raw: dict[str, Any]
+
+ @property
+ def run_id(self) -> str:
+ return str(self.raw["run_id"])
+
+ @property
+ def accepted(self) -> int:
+ return int(self.raw["accepted_events"])
+
+ @property
+ def attempted(self) -> int:
+ return int(self.raw["attempted_events"])
+
+ @property
+ def wall_seconds(self) -> float:
+ return float(self.raw["wall_seconds"])
+
+ @property
+ def accepted_eps(self) -> float:
+ return float(self.raw["accepted_eps"])
+
+
+@dataclass
+class AlertRow:
+ seq: int
+ sent_epoch: float
+ created_epoch: float
+
+
+@dataclass
+class ResourceSample:
+ at: float
+ rows: dict[str, dict[str, str]] = field(default_factory=dict)
+
+
+def hardware_fingerprint() -> dict[str, Any]:
+ """Where the number came from. Published beside every figure, always."""
+ info: dict[str, Any] = {
+ "os": f"{platform.system()} {platform.release()}",
+ "arch": platform.machine(),
+ "python": platform.python_version(),
+ "cpu_count": os.cpu_count(),
+ }
+ if platform.system() == "Darwin":
+ for key, label in (("machdep.cpu.brand_string", "cpu"), ("hw.memsize", "memory_bytes")):
+ out = subprocess.run(["sysctl", "-n", key], capture_output=True, text=True, check=False) # noqa: S603
+ if out.returncode == 0 and out.stdout.strip():
+ info[label] = out.stdout.strip()
+ elif platform.system() == "Linux":
+ try:
+ for line in Path("/proc/cpuinfo").read_text(encoding="utf-8").splitlines():
+ if line.startswith("model name"):
+ info["cpu"] = line.split(":", 1)[1].strip()
+ break
+ for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines():
+ if line.startswith("MemTotal"):
+ info["memory_bytes"] = str(int(line.split()[1]) * 1024)
+ break
+ except OSError:
+ # Host CPU and memory are descriptive context printed beside the
+ # measurement, not inputs to it. /proc is absent on macOS and on
+ # some containers, and a run that cannot name the hardware is still
+ # a valid run — so the keys stay unset rather than failing here.
+ pass
+ if shutil.which("docker"):
+ out = subprocess.run( # noqa: S603
+ ["docker", "info", "--format", "{{.ServerVersion}}|{{.NCPU}}|{{.MemTotal}}"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if out.returncode == 0 and "|" in out.stdout:
+ version, ncpu, memtotal = out.stdout.strip().split("|", 2)
+ info["container_runtime"] = f"docker {version}"
+ info["runtime_cpus"] = ncpu
+ info["runtime_memory_bytes"] = memtotal
+ if os.environ.get("GITHUB_ACTIONS") == "true":
+ info["ci_runner"] = os.environ.get("RUNNER_NAME") or "github-actions"
+ info["ci_os"] = os.environ.get("ImageOS") or os.environ.get("RUNNER_OS", "")
+ return info
+
+
+def measure_clock_offset(target: Target, rounds: int = 5) -> tuple[float, float]:
+ """Seconds to add to a database timestamp to express it in this clock.
+
+ The producer stamps its own clock into every title and the database stamps
+ ``created_at`` with its own. Subtracting one from the other without this
+ correction publishes the offset between two machines as pipeline latency.
+ Measured by bracketing each query with local reads and taking the midpoint,
+ so the round trip itself does not enter the estimate. Returns the median
+ offset and the spread, and the spread is published: a wide one means the
+ latency figures carry that much uncertainty.
+ """
+ offsets: list[float] = []
+ for _ in range(rounds):
+ before = time.time()
+ db_epoch = float(target.sql("select extract(epoch from clock_timestamp())"))
+ after = time.time()
+ offsets.append(((before + after) / 2.0) - db_epoch)
+ offsets.sort()
+ spread = offsets[-1] - offsets[0]
+ return statistics.median(offsets), spread
+
+
+def run_producer(
+ *,
+ producer_bin: str | None,
+ root: Path,
+ ingest_url: str,
+ token: str,
+ tenant: str,
+ events: int,
+ workers: int,
+ batch: int,
+ target_eps: int,
+ run_id: str,
+ summary_path: Path,
+) -> ProducerSummary:
+ if producer_bin:
+ argv = [producer_bin]
+ else:
+ if not shutil.which("go"):
+ raise RuntimeError("no --producer-bin given and `go` is not on PATH to build services/demo-producer")
+ argv = ["go", "run", "./services/demo-producer"]
+ argv += [
+ "--load",
+ "--ingest-url",
+ ingest_url,
+ "--token",
+ token,
+ "--tenant",
+ tenant,
+ "--total",
+ str(events),
+ "--workers",
+ str(workers),
+ "--batch",
+ str(batch),
+ "--target-eps",
+ str(target_eps),
+ "--run-id",
+ run_id,
+ "--summary",
+ str(summary_path),
+ ]
+ done = subprocess.run(argv, cwd=root, capture_output=True, text=True, check=False) # noqa: S603
+ if done.returncode != 0:
+ raise RuntimeError(f"producer failed ({done.returncode}): {(done.stderr or done.stdout).strip()[-600:]}")
+ return ProducerSummary(json.loads(summary_path.read_text(encoding="utf-8")))
+
+
+def collect_alerts(target: Target, run_id: str) -> list[AlertRow]:
+ query = f"select title, extract(epoch from created_at) from alerts where title like '{MARKER_PREFIX} {run_id} %'"
+ rows: list[AlertRow] = []
+ for line in target.sql(query, timeout=300).splitlines():
+ if "|" not in line:
+ continue
+ title, created = line.rsplit("|", 1)
+ match = _TITLE_RE.match(title.strip())
+ if not match or match.group("run") != run_id:
+ continue
+ rows.append(
+ AlertRow(
+ seq=int(match.group("seq")),
+ sent_epoch=int(match.group("sent")) / 1e9,
+ created_epoch=float(created),
+ )
+ )
+ return rows
+
+
+def sample_resources(target: Target) -> ResourceSample:
+ sample = ResourceSample(at=time.time())
+ if not target.stats:
+ return sample
+ try:
+ done = subprocess.run(target.stats, capture_output=True, text=True, timeout=45, check=False) # noqa: S603
+ except (OSError, subprocess.TimeoutExpired):
+ return sample
+ if done.returncode != 0:
+ return sample
+ for line in done.stdout.splitlines():
+ fields = line.split("\t") if "\t" in line else line.split()
+ if len(fields) < 3:
+ continue
+ name = fields[0]
+ short = name.replace("aisoc-", "").split("-")[0]
+ if short not in _RESOURCE_SERVICES:
+ continue
+ sample.rows[short] = {"cpu": fields[1], "memory": " ".join(fields[2:])}
+ return sample
+
+
+def build_report(
+ *,
+ target: Target,
+ summary: ProducerSummary,
+ alerts: list[AlertRow],
+ clock_offset: float,
+ clock_spread: float,
+ lag_in_flight: tuple[int | None, str],
+ lag_drained: tuple[int | None, str],
+ dead_letters: int | None,
+ dead_letter_reason: str,
+ resources: list[ResourceSample],
+ drain_seconds: float,
+ settled: bool,
+) -> dict[str, Any]:
+ accepted = summary.accepted
+ seen: dict[int, int] = {}
+ for row in alerts:
+ seen[row.seq] = seen.get(row.seq, 0) + 1
+ duplicates = sum(count - 1 for count in seen.values() if count > 1)
+ missing = accepted - len(seen)
+
+ latencies_ms: list[float] = sorted(((row.created_epoch + clock_offset) - row.sent_epoch) * 1000.0 for row in alerts)
+
+ metrics: dict[str, Measurement] = {}
+ if latencies_ms:
+ metrics["latency_p50_ms"] = measured("latency_p50_ms", "ms", percentile(latencies_ms, 0.50), len(latencies_ms))
+ metrics["latency_p95_ms"] = measured("latency_p95_ms", "ms", percentile(latencies_ms, 0.95), len(latencies_ms))
+ metrics["latency_p99_ms"] = measured("latency_p99_ms", "ms", percentile(latencies_ms, 0.99), len(latencies_ms))
+ metrics["latency_max_ms"] = measured("latency_max_ms", "ms", latencies_ms[-1], len(latencies_ms))
+ else:
+ why = "no alert rows carried this run's marker"
+ for name in ("latency_p50_ms", "latency_p95_ms", "latency_p99_ms", "latency_max_ms"):
+ metrics[name] = unmeasured(name, "ms", why)
+
+ metrics["ingest_accepted_eps"] = (
+ measured("ingest_accepted_eps", "events/s", summary.accepted_eps, accepted)
+ if accepted > 0
+ else unmeasured("ingest_accepted_eps", "events/s", "ingest accepted no events")
+ )
+
+ if len(alerts) >= 2:
+ span = max(r.created_epoch for r in alerts) - min(r.created_epoch for r in alerts)
+ metrics["pipeline_eps"] = (
+ measured("pipeline_eps", "alerts/s", len(alerts) / span, len(alerts))
+ if span > 0
+ else unmeasured("pipeline_eps", "alerts/s", "every alert carried the same timestamp; span too short to divide")
+ )
+ else:
+ metrics["pipeline_eps"] = unmeasured("pipeline_eps", "alerts/s", "fewer than two alerts landed")
+
+ metrics["delivery_ratio"] = (
+ measured("delivery_ratio", "fraction", len(seen) / accepted, accepted)
+ if accepted > 0
+ else unmeasured("delivery_ratio", "fraction", "ingest accepted no events")
+ )
+
+ for key, (value, reason) in (("consumer_lag_in_flight", lag_in_flight), ("consumer_lag_drained", lag_drained)):
+ metrics[key] = measured(key, "messages", float(value), 1) if value is not None else unmeasured(key, "messages", reason)
+
+ if dead_letters is not None and summary.attempted > 0:
+ metrics["dead_letter_rate"] = measured("dead_letter_rate", "fraction", dead_letters / summary.attempted, summary.attempted)
+ else:
+ metrics["dead_letter_rate"] = unmeasured("dead_letter_rate", "fraction", dead_letter_reason or "no attempted events")
+
+ return {
+ "schema": "aisoc.load_harness/v1",
+ # Every published figure carries these two. check_perf_results.py
+ # fails a committed result that drops either, because a throughput
+ # number without the machine and the date is not a measurement.
+ "measured_at": datetime.now(UTC).isoformat(timespec="seconds"),
+ "hardware": hardware_fingerprint(),
+ "deployment": target.name,
+ "not_a_production_slo": True,
+ "slo_disclaimer": (
+ "These are measurements of one deployment on the hardware named above, on the date named "
+ "above. They are not a service-level objective and no support commitment is derived from "
+ "them. Sustained throughput on other hardware, other storage and other event mixes will "
+ "differ. The regression floors in perf.yml are set well below the measured values so they "
+ "fire on a catastrophic regression rather than on runner jitter."
+ ),
+ "run": {
+ "run_id": summary.run_id,
+ "attempted_events": summary.attempted,
+ "accepted_events": accepted,
+ "alerts_observed": len(alerts),
+ "distinct_events_alerted": len(seen),
+ "missing_events": missing,
+ "duplicate_alert_rows": duplicates,
+ "push_wall_seconds": summary.wall_seconds,
+ "drain_wall_seconds": drain_seconds,
+ "drain_settled": settled,
+ "clock_offset_seconds": clock_offset,
+ "clock_offset_spread_seconds": clock_spread,
+ "producer": summary.raw,
+ },
+ "metrics": {name: m.as_dict() for name, m in sorted(metrics.items())},
+ "resources": [{"at": datetime.fromtimestamp(s.at, tz=UTC).isoformat(timespec="seconds"), "containers": s.rows} for s in resources],
+ }
+
+
+def render_text(report: dict[str, Any]) -> str:
+ hw = report["hardware"]
+ lines = [
+ f"AiSOC load harness · {report['deployment']} · {report['measured_at']}",
+ f" hardware: {hw.get('cpu', hw.get('arch'))} · {hw.get('cpu_count')} cpu · runtime {hw.get('container_runtime', 'n/a')}",
+ " NOT A PRODUCTION SLO. One deployment, this hardware, this date.",
+ "",
+ ]
+ run = report["run"]
+ lines.append(
+ f" events: {run['accepted_events']:,} accepted of {run['attempted_events']:,} attempted; "
+ f"{run['distinct_events_alerted']:,} alerted, {run['missing_events']:,} missing, "
+ f"{run['duplicate_alert_rows']:,} duplicate rows"
+ )
+ lines.append("")
+ for name, body in report["metrics"].items():
+ if body["measured"]:
+ lines.append(f" {name:<26} {body['value']:>14,.2f} {body['unit']} (n={body['samples']:,})")
+ else:
+ lines.append(f" {name:<26} {'not measured':>14} ({body['reason']})")
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--target", choices=("compose", "kubernetes"), default="compose")
+ parser.add_argument("--events", type=int, default=20000, help="events to push")
+ parser.add_argument("--workers", type=int, default=8)
+ parser.add_argument("--batch", type=int, default=50)
+ parser.add_argument("--target-eps", type=int, default=0, help="0 saturates; otherwise pace to this rate")
+ parser.add_argument("--token", default=os.environ.get("AISOC_INGEST_TOKEN", ""))
+ parser.add_argument("--tenant", default=os.environ.get("AISOC_TENANT_ID", _DEFAULT_TENANT))
+ parser.add_argument("--ingest-url", default=os.environ.get("AISOC_INGEST_URL", "http://localhost:8081/v1/ingest/batch"))
+ parser.add_argument("--compose-file", action="append", default=[], help="repeatable; passed to docker compose -f")
+ parser.add_argument("--namespace", default="aisoc")
+ parser.add_argument("--release", default="aisoc")
+ parser.add_argument("--postgres-ref", default="statefulset/postgres", help="kubernetes: what to `kubectl exec` psql in")
+ parser.add_argument("--kafka-ref", default="statefulset/aisoc-kafka", help="kubernetes: what to `kubectl exec` kafka tools in")
+ parser.add_argument(
+ "--producer-bin", default=os.environ.get("AISOC_PRODUCER_BIN", ""), help="prebuilt demo-producer; otherwise `go run`"
+ )
+ parser.add_argument("--drain-timeout", type=int, default=300, help="seconds to wait for alerts to stop arriving")
+ parser.add_argument("--json", action="store_true", help="print the report as JSON")
+ parser.add_argument("--out", type=Path, help="write the JSON report here")
+ parser.add_argument("--assert-eps-floor", type=float, help="fail if pipeline throughput is below this")
+ parser.add_argument("--assert-p95-ceiling-ms", type=float, help="fail if p95 event-to-alert latency exceeds this")
+ parser.add_argument("--assert-no-loss", action="store_true", help="fail if any accepted event produced no alert")
+ args = parser.parse_args(argv)
+
+ root = repo_root()
+ if not (root / "services" / "demo-producer").is_dir():
+ print("load_harness: services/demo-producer is not in this tree; nothing to drive", file=sys.stderr)
+ return 2
+ if not args.token:
+ print(
+ "load_harness: no ingest credential. Pass --token or set AISOC_INGEST_TOKEN "
+ "(`make ingest-token`). /v1/ingest/batch refuses an unauthenticated push.",
+ file=sys.stderr,
+ )
+ return 2
+
+ compose_files = args.compose_file or ["docker-compose.yml"]
+ target = (
+ compose_target(root, compose_files, args.ingest_url)
+ if args.target == "compose"
+ else kubernetes_target(args.namespace, args.release, args.ingest_url, args.postgres_ref, args.kafka_ref)
+ )
+
+ try:
+ clock_offset, clock_spread = measure_clock_offset(target)
+ except (RuntimeError, ValueError, subprocess.SubprocessError) as exc:
+ print(f"load_harness: cannot reach the alert store, so nothing can be measured: {exc}", file=sys.stderr)
+ return 2
+
+ run_id = f"p{int(time.time()) % 100000000:08d}"
+ baseline_dl = target.sql("select count(*) from aisoc_dead_letters")
+ summary_path = Path(os.environ.get("TMPDIR", "/tmp")) / f"aisoc-load-{run_id}.json"
+
+ resources: list[ResourceSample] = []
+ push_started = time.time()
+ summary = run_producer(
+ producer_bin=args.producer_bin or None,
+ root=root,
+ ingest_url=args.ingest_url,
+ token=args.token,
+ tenant=args.tenant,
+ events=args.events,
+ workers=args.workers,
+ batch=args.batch,
+ target_eps=args.target_eps,
+ run_id=run_id,
+ summary_path=summary_path,
+ )
+ # Sampled immediately after the push rather than after the drain: the
+ # queue is at its deepest here, and a lag read once the pipeline has caught
+ # up is zero however far behind it got.
+ lag_in_flight = target.kafka_lag(_FUSION_GROUP)
+ resources.append(sample_resources(target))
+
+ drain_started = time.time()
+ previous = -1
+ settled = False
+ while time.time() - drain_started < args.drain_timeout:
+ count = int(target.sql(f"select count(*) from alerts where title like '{MARKER_PREFIX} {run_id} %'") or 0)
+ if count >= summary.accepted:
+ settled = True
+ break
+ if count == previous and count > 0:
+ # Two identical reads five seconds apart with events still missing.
+ # Stop waiting and report the shortfall rather than burning the
+ # timeout: a stalled consumer is the finding.
+ settled = True
+ break
+ previous = count
+ if len(resources) < 12:
+ resources.append(sample_resources(target))
+ time.sleep(5)
+ drain_seconds = time.time() - drain_started
+
+ alerts = collect_alerts(target, run_id)
+ lag_drained = target.kafka_lag(_FUSION_GROUP)
+ try:
+ after_dl = int(target.sql("select count(*) from aisoc_dead_letters") or 0)
+ dead_letters: int | None = max(0, after_dl - int(baseline_dl or 0))
+ dl_reason = ""
+ except (RuntimeError, ValueError) as exc:
+ dead_letters, dl_reason = None, f"dead-letter table unreadable: {exc}"
+
+ report = build_report(
+ target=target,
+ summary=summary,
+ alerts=alerts,
+ clock_offset=clock_offset,
+ clock_spread=clock_spread,
+ lag_in_flight=lag_in_flight,
+ lag_drained=lag_drained,
+ dead_letters=dead_letters,
+ dead_letter_reason=dl_reason,
+ resources=resources,
+ drain_seconds=drain_seconds,
+ settled=settled,
+ )
+ report["run"]["total_wall_seconds"] = time.time() - push_started
+
+ if args.out:
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps(report, indent=2) if args.json else render_text(report))
+
+ failures: list[str] = []
+ metrics = report["metrics"]
+ if args.assert_eps_floor is not None:
+ body = metrics["pipeline_eps"]
+ if not body["measured"]:
+ failures.append(f"pipeline throughput was not measured ({body['reason']}), so the floor cannot be met")
+ elif body["value"] < args.assert_eps_floor:
+ failures.append(f"pipeline throughput {body['value']:.1f}/s is below the floor {args.assert_eps_floor:.1f}/s")
+ if args.assert_p95_ceiling_ms is not None:
+ body = metrics["latency_p95_ms"]
+ if not body["measured"]:
+ failures.append(f"p95 latency was not measured ({body['reason']}), so the ceiling cannot be met")
+ elif body["value"] > args.assert_p95_ceiling_ms:
+ failures.append(f"p95 latency {body['value']:.0f}ms exceeds the ceiling {args.assert_p95_ceiling_ms:.0f}ms")
+ if args.assert_no_loss and report["run"]["missing_events"] > 0:
+ failures.append(f"{report['run']['missing_events']} accepted events produced no alert")
+
+ for failure in failures:
+ print(f"FAIL: {failure}", file=sys.stderr)
+ return 1 if failures else 0
+
+
+def _self_test() -> int:
+ """Prove the two properties a reader has to trust before believing a number."""
+ checks: list[tuple[str, bool]] = []
+
+ empty = build_report(
+ target=Target(name="t", psql=[], kafka=[], stats=None, ingest_url=""),
+ summary=ProducerSummary(
+ {
+ "run_id": "x",
+ "attempted_events": 10,
+ "accepted_events": 0,
+ "wall_seconds": 1.0,
+ "accepted_eps": 0.0,
+ }
+ ),
+ alerts=[],
+ clock_offset=0.0,
+ clock_spread=0.0,
+ lag_in_flight=(None, "broker unreachable"),
+ lag_drained=(None, "broker unreachable"),
+ dead_letters=None,
+ dead_letter_reason="table unreadable",
+ resources=[],
+ drain_seconds=0.0,
+ settled=False,
+ )
+ unmeasured_bodies = [body for body in empty["metrics"].values() if not body["measured"]]
+ checks.append(
+ (
+ "a run that measured nothing emits no `value` key anywhere, so no formatter can render it as 0",
+ len(unmeasured_bodies) == len(empty["metrics"]) and all("value" not in b for b in unmeasured_bodies),
+ )
+ )
+ checks.append(
+ (
+ "every unmeasured metric carries the reason it was not measured",
+ all(b.get("reason") for b in unmeasured_bodies),
+ )
+ )
+
+ real = build_report(
+ target=Target(name="t", psql=[], kafka=[], stats=None, ingest_url=""),
+ summary=ProducerSummary({"run_id": "x", "attempted_events": 3, "accepted_events": 3, "wall_seconds": 1.0, "accepted_eps": 3.0}),
+ alerts=[AlertRow(seq=i, sent_epoch=100.0, created_epoch=100.0 + (i + 1) / 10) for i in range(3)],
+ clock_offset=0.0,
+ clock_spread=0.0,
+ lag_in_flight=(7, ""),
+ lag_drained=(0, ""),
+ dead_letters=0,
+ dead_letter_reason="",
+ resources=[],
+ drain_seconds=1.0,
+ settled=True,
+ )
+ checks.append(
+ (
+ "a real zero stays a zero: 0 dead letters and 0 drained lag are measured values, not absences",
+ real["metrics"]["dead_letter_rate"] == {"unit": "fraction", "measured": True, "samples": 3, "value": 0.0}
+ and real["metrics"]["consumer_lag_drained"]["value"] == 0.0,
+ )
+ )
+ checks.append(
+ (
+ "latency is corrected for the clock offset rather than assuming the two clocks agree",
+ build_report(
+ target=Target(name="t", psql=[], kafka=[], stats=None, ingest_url=""),
+ summary=ProducerSummary(
+ {"run_id": "x", "attempted_events": 1, "accepted_events": 1, "wall_seconds": 1.0, "accepted_eps": 1.0}
+ ),
+ alerts=[AlertRow(seq=0, sent_epoch=100.0, created_epoch=105.0)],
+ clock_offset=-4.0,
+ clock_spread=0.0,
+ lag_in_flight=(0, ""),
+ lag_drained=(0, ""),
+ dead_letters=0,
+ dead_letter_reason="",
+ resources=[],
+ drain_seconds=0.0,
+ settled=True,
+ )["metrics"]["latency_p50_ms"]["value"]
+ == 1000.0,
+ )
+ )
+ # Two accepted events, but both alert rows carry seq=0: one event was
+ # duplicated and one never arrived. Both have to be visible, because a
+ # count of rows alone reads as full delivery.
+ doubled = build_report(
+ target=Target(name="t", psql=[], kafka=[], stats=None, ingest_url=""),
+ summary=ProducerSummary({"run_id": "x", "attempted_events": 2, "accepted_events": 2, "wall_seconds": 1.0, "accepted_eps": 2.0}),
+ alerts=[AlertRow(seq=0, sent_epoch=1.0, created_epoch=1.1), AlertRow(seq=0, sent_epoch=1.0, created_epoch=1.2)],
+ clock_offset=0.0,
+ clock_spread=0.0,
+ lag_in_flight=(0, ""),
+ lag_drained=(0, ""),
+ dead_letters=0,
+ dead_letter_reason="",
+ resources=[],
+ drain_seconds=0.0,
+ settled=True,
+ )
+ checks.append(
+ (
+ "two rows for one sequence number report one duplicate and one loss, not two deliveries",
+ doubled["run"]["duplicate_alert_rows"] == 1
+ and doubled["run"]["missing_events"] == 1
+ and doubled["run"]["alerts_observed"] == 2,
+ )
+ )
+
+ title = f"{MARKER_PREFIX} run1 seq=12 t=1700000000123456789"
+ match = _TITLE_RE.match(title)
+ # `match is not None` rather than `bool(match)`: only the former narrows the
+ # Optional for the `.group` call on the same line.
+ checks.append(("the marker this harness matches is the marker the producer writes", match is not None and match.group("seq") == "12"))
+
+ ok = True
+ for description, passed in checks:
+ ok &= passed
+ print(f" {'PASS' if passed else 'FAIL'} {description}")
+ print()
+ print("load_harness.py: self-test " + ("OK" if ok else "FAILED"))
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ if "--self-test" in sys.argv[1:]:
+ # The shared empty-tree refusal, plus the properties only this file can
+ # express. Both have to hold: a harness that cannot tell "measured 0"
+ # from "did not measure" is worse than no harness.
+ #
+ # The path is passed relative to ``scripts/`` rather than through
+ # ``self_test_if_requested``, which takes a basename: this file lives
+ # in ``scripts/perf/`` and the probe would have launched
+ # ``scripts/load_harness.py``, which does not exist. A missing file
+ # exits non-zero, so the refusal would have passed while proving
+ # nothing at all about this harness.
+ sys.exit(_self_test() or self_test_main("perf/load_harness.py", []))
+ sys.exit(main())
diff --git a/services/demo-producer/main.go b/services/demo-producer/main.go
index 5b6114627..6af39c36d 100644
--- a/services/demo-producer/main.go
+++ b/services/demo-producer/main.go
@@ -14,6 +14,29 @@
//
// `--rate` is events per second per connector. `--duration 0` runs forever.
//
+// # Load mode
+//
+// `--load` switches from "keep a dashboard populated" to "measure what the
+// spine sustains". It replaces the six randomised connector profiles with one
+// deterministic event shape whose title carries a run id, a sequence number
+// and the send time in Unix nanoseconds, so every alert that reaches Postgres
+// can be attributed to the exact event that produced it. Each event also
+// carries its own host, because the fusion correlation key is
+// {tenant}:{entity}:{tactic}: shared entities would collapse thousands of
+// events into a handful of alerts and there would be nothing per-event left
+// to time. That makes load mode the worst case for fusion and the alert
+// store, which is the case worth publishing.
+//
+// go run ./services/demo-producer --load \
+// --ingest-url http://localhost:8081/v1/ingest/batch \
+// --token "$AISOC_INGEST_TOKEN" \
+// --total 20000 --workers 8 --batch 50 \
+// --summary /tmp/producer.json
+//
+// `scripts/perf/load_harness.py` drives this and correlates the summary with
+// the alert rows. Nothing here measures latency: this end knows only when it
+// sent, and the other end of the clock lives in the database.
+//
// Part of the AiSOC platform (MIT License).
package main
@@ -27,6 +50,8 @@ import (
"net/http"
"os"
"os/signal"
+ "sort"
+ "strconv"
"sync"
"sync/atomic"
"syscall"
@@ -199,7 +224,97 @@ var profiles = []connectorProfile{
{id: "demo-splunk", typ: "splunk", format: "splunk-event", build: splunkEvent},
}
-func runProducer(ctx context.Context, wg *sync.WaitGroup, profile connectorProfile, opts options, sent *atomic.Int64) {
+// stats counts what happened to each event, not how many were handed to the
+// HTTP client. The producer used to add len(batch) to one counter immediately
+// after Do() returned, without reading the status: a stack answering 401 or
+// 500 to every batch still reported full throughput. A load harness built on
+// that number would publish the throughput of an ingest endpoint that
+// accepted nothing.
+type stats struct {
+ attempted atomic.Int64 // events handed to ingest
+ accepted atomic.Int64 // events ingest said it took
+ rejected atomic.Int64 // events ingest parsed and refused
+ refused atomic.Int64 // events in batches answered with a non-2xx
+ transport atomic.Int64 // events in batches that never got an answer
+
+ mu sync.Mutex
+ statuses map[int]int64
+}
+
+func newStats() *stats { return &stats{statuses: map[int]int64{}} }
+
+func (s *stats) recordStatus(code int) {
+ s.mu.Lock()
+ s.statuses[code]++
+ s.mu.Unlock()
+}
+
+func (s *stats) statusCounts() map[string]int64 {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := make(map[string]int64, len(s.statuses))
+ for code, n := range s.statuses {
+ out[strconv.Itoa(code)] = n
+ }
+ return out
+}
+
+// ingestResponse is the shape /v1/ingest/batch answers with. Both counters are
+// read rather than inferred: a 200 whose body says `rejected: 50` is not a
+// batch that landed.
+type ingestResponse struct {
+ Accepted int `json:"accepted"`
+ Rejected int `json:"rejected"`
+}
+
+// errFatalRequest marks the one failure in the send loop that retrying cannot
+// clear: a URL that will not parse never becomes one that will.
+var errFatalRequest = fmt.Errorf("request cannot be built")
+
+func postBatch(ctx context.Context, client *http.Client, opts options, payload ingestRequest, st *stats) error {
+ n := int64(len(payload.Events))
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("marshal: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", opts.ingestURL, bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("%w for %q: %v", errFatalRequest, opts.ingestURL, err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Tenant-ID", opts.tenant)
+ // /v1/ingest derives the tenant from the credential and only intersects
+ // the header above with it, so without a token every batch is refused
+ // with 401.
+ if opts.token != "" {
+ req.Header.Set("Authorization", "Bearer "+opts.token)
+ }
+
+ st.attempted.Add(n)
+ resp, err := client.Do(req)
+ if err != nil {
+ st.transport.Add(n)
+ return err
+ }
+ defer resp.Body.Close()
+ st.recordStatus(resp.StatusCode)
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ st.refused.Add(n)
+ return fmt.Errorf("ingest answered HTTP %d", resp.StatusCode)
+ }
+ var decoded ingestResponse
+ if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil {
+ // A 2xx whose body we cannot read is not evidence the events landed,
+ // so it is counted as refused rather than credited.
+ st.refused.Add(n)
+ return fmt.Errorf("ingest answered HTTP %d with an unreadable body: %w", resp.StatusCode, err)
+ }
+ st.accepted.Add(int64(decoded.Accepted))
+ st.rejected.Add(int64(decoded.Rejected))
+ return nil
+}
+
+func runProducer(ctx context.Context, wg *sync.WaitGroup, profile connectorProfile, opts options, st *stats) {
defer wg.Done()
r := rand.New(rand.NewSource(time.Now().UnixNano() + int64(len(profile.id))))
interval := time.Second / time.Duration(opts.rate)
@@ -220,49 +335,222 @@ func runProducer(ctx context.Context, wg *sync.WaitGroup, profile connectorProfi
for i := 0; i < opts.batch; i++ {
batch = append(batch, profile.build(r))
}
- payload := ingestRequest{
+ err := postBatch(ctx, client, opts, ingestRequest{
ConnectorID: profile.id,
ConnectorType: profile.typ,
SourceFormat: profile.format,
Events: batch,
- }
- body, err := json.Marshal(payload)
- if err != nil {
- fmt.Fprintf(os.Stderr, "[%s] marshal: %v\n", profile.id, err)
+ }, st)
+ if err == nil {
continue
}
- req, err := http.NewRequestWithContext(ctx, "POST", opts.ingestURL, bytes.NewReader(body))
- if err != nil {
- // 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)
+ if errors := ctx.Err(); errors != nil {
return
}
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("X-Tenant-ID", opts.tenant)
- // /v1/ingest derives the tenant from the credential and only
- // intersects the header above with it, so without a token every
- // batch is refused with 401.
- if opts.token != "" {
- req.Header.Set("Authorization", "Bearer "+opts.token)
+ fmt.Fprintf(os.Stderr, "[%s] %v\n", profile.id, err)
+ if isFatalRequest(err) {
+ fmt.Fprintf(os.Stderr, "[%s] this will not resolve; fix --ingest-url\n", profile.id)
+ return
}
- resp, err := client.Do(req)
- if err != nil {
- if ctx.Err() == nil {
- fmt.Fprintf(os.Stderr, "[%s] post: %v\n", profile.id, err)
+ }
+ }
+}
+
+func isFatalRequest(err error) bool {
+ for err != nil {
+ if err == errFatalRequest {
+ return true
+ }
+ type unwrapper interface{ Unwrap() error }
+ u, ok := err.(unwrapper)
+ if !ok {
+ return false
+ }
+ err = u.Unwrap()
+ }
+ return false
+}
+
+// ── Load mode ───────────────────────────────────────────────────────────────
+
+// MarkerPrefix opens the title of every load event. `scripts/perf/load_harness.py`
+// matches alert rows on it, so the two must agree; it is a constant here and a
+// constant there, and the harness fails loudly when it finds none rather than
+// publishing a throughput figure over zero correlated alerts.
+const MarkerPrefix = "aisoc-load"
+
+// loadEvent is one deterministic endpoint detection, shaped like the event the
+// golden pipeline pushes so it takes the same promotion path a real detection
+// takes. Three things are per-event and load-bearing:
+//
+// seq attributes the alert back to the event that made it, which is what
+// makes "no loss and no duplicates" a countable statement.
+// sentNanos is the send time in the producer's clock. The harness subtracts
+// it from the alert's created_at, correcting for the measured offset
+// between the two clocks rather than assuming they agree.
+// host is unique per event so the fusion correlation key
+// {tenant}:{entity}:{tactic} does not collapse the run into a handful
+// of alerts.
+func loadEvent(runID string, seq int64, sentNanos int64) map[string]interface{} {
+ host := fmt.Sprintf("LOAD-%s-%06d", runID, seq)
+ return map[string]interface{}{
+ "severity": "high",
+ "title": fmt.Sprintf("%s %s seq=%d t=%d", MarkerPrefix, runID, seq, sentNanos),
+ "description": fmt.Sprintf("winword.exe spawned powershell.exe with an encoded command line on %s", host),
+ "host": host,
+ "user": fmt.Sprintf("loaduser%03d", seq%200),
+ "process_name": "powershell.exe",
+ "parent_process": "winword.exe",
+ "command_line": "powershell.exe -nop -w hidden -enc JABzAD0A",
+ "event_type": "process_create",
+ "technique": "T1059.001",
+ "timestamp": time.Unix(0, sentNanos).UTC().Format(time.RFC3339Nano),
+ }
+}
+
+type loadSummary struct {
+ RunID string `json:"run_id"`
+ Mode string `json:"mode"`
+ MarkerPrefix string `json:"marker_prefix"`
+ IngestURL string `json:"ingest_url"`
+ Tenant string `json:"tenant"`
+ StartedAt string `json:"started_at"`
+ EndedAt string `json:"ended_at"`
+ WallSeconds float64 `json:"wall_seconds"`
+ Workers int `json:"workers"`
+ BatchSize int `json:"batch_size"`
+ TargetEPS int `json:"target_eps"`
+ Requested int64 `json:"requested_events"`
+ Attempted int64 `json:"attempted_events"`
+ Accepted int64 `json:"accepted_events"`
+ Rejected int64 `json:"rejected_events"`
+ Refused int64 `json:"refused_events"`
+ TransportErrors int64 `json:"transport_error_events"`
+ AcceptedEPS float64 `json:"accepted_eps"`
+ StatusCounts map[string]int64 `json:"http_status_counts"`
+ SeqLow int64 `json:"seq_low"`
+ SeqHigh int64 `json:"seq_high"`
+}
+
+// runLoad saturates or paces ingest with `total` attributable events and
+// returns what happened. It never returns a throughput figure for events that
+// were not accepted: `accepted_eps` divides the accepted count, so an ingest
+// that refuses everything reports zero rather than the rate at which it
+// refused.
+func runLoad(ctx context.Context, opts options) loadSummary {
+ st := newStats()
+ var seq atomic.Int64
+ var issued atomic.Int64
+
+ // A shared bucket rather than a per-worker ticker: pacing per worker makes
+ // the aggregate rate depend on how many workers happen to be blocked.
+ var pace <-chan time.Time
+ if opts.targetEPS > 0 {
+ batchesPerSecond := float64(opts.targetEPS) / float64(opts.batch)
+ if batchesPerSecond < 1 {
+ batchesPerSecond = 1
+ }
+ ticker := time.NewTicker(time.Duration(float64(time.Second) / batchesPerSecond))
+ defer ticker.Stop()
+ pace = ticker.C
+ }
+
+ started := time.Now()
+ var wg sync.WaitGroup
+ for w := 0; w < opts.workers; w++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ client := &http.Client{Timeout: 30 * time.Second}
+ for {
+ if ctx.Err() != nil {
+ return
+ }
+ if opts.total > 0 && issued.Load() >= opts.total {
+ return
+ }
+ if pace != nil {
+ select {
+ case <-ctx.Done():
+ return
+ case <-pace:
+ }
+ }
+ size := opts.batch
+ if opts.total > 0 {
+ remaining := opts.total - issued.Add(int64(size))
+ if remaining < 0 {
+ size += int(remaining) // the last batch is short, never over
+ if size <= 0 {
+ return
+ }
+ }
+ }
+ batch := make([]map[string]interface{}, 0, size)
+ now := time.Now().UnixNano()
+ for i := 0; i < size; i++ {
+ batch = append(batch, loadEvent(opts.runID, seq.Add(1)-1, now))
+ }
+ err := postBatch(ctx, client, opts, ingestRequest{
+ ConnectorID: "load-" + opts.runID,
+ ConnectorType: "crowdstrike",
+ SourceFormat: "json",
+ Events: batch,
+ }, st)
+ if err != nil && ctx.Err() == nil {
+ fmt.Fprintf(os.Stderr, "[load] %v\n", err)
+ if isFatalRequest(err) {
+ return
+ }
}
- continue
}
- resp.Body.Close()
- sent.Add(int64(len(batch)))
- }
+ }()
+ }
+ wg.Wait()
+ elapsed := time.Since(started)
+
+ accepted := st.accepted.Load()
+ eps := 0.0
+ if elapsed.Seconds() > 0 {
+ eps = float64(accepted) / elapsed.Seconds()
+ }
+ high := seq.Load() - 1
+ if high < 0 {
+ high = 0
+ }
+ return loadSummary{
+ RunID: opts.runID,
+ Mode: "load",
+ MarkerPrefix: MarkerPrefix,
+ IngestURL: opts.ingestURL,
+ Tenant: opts.tenant,
+ StartedAt: started.UTC().Format(time.RFC3339Nano),
+ EndedAt: started.Add(elapsed).UTC().Format(time.RFC3339Nano),
+ WallSeconds: elapsed.Seconds(),
+ Workers: opts.workers,
+ BatchSize: opts.batch,
+ TargetEPS: opts.targetEPS,
+ Requested: opts.total,
+ Attempted: st.attempted.Load(),
+ Accepted: accepted,
+ Rejected: st.rejected.Load(),
+ Refused: st.refused.Load(),
+ TransportErrors: st.transport.Load(),
+ AcceptedEPS: eps,
+ StatusCounts: st.statusCounts(),
+ SeqLow: 0,
+ SeqHigh: high,
}
}
+func writeSummary(path string, summary loadSummary) error {
+ blob, err := json.MarshalIndent(summary, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, append(blob, '\n'), 0o600)
+}
+
type options struct {
ingestURL string
tenant string
@@ -270,6 +558,13 @@ type options struct {
rate int
batch int
duration time.Duration
+
+ load bool
+ runID string
+ total int64
+ workers int
+ targetEPS int
+ summary string
}
func main() {
@@ -280,11 +575,14 @@ func main() {
flag.IntVar(&opts.rate, "rate", 4, "Batches per second per connector")
flag.IntVar(&opts.batch, "batch", 5, "Events per batch")
flag.DurationVar(&opts.duration, "duration", 0, "How long to run (0 = forever)")
+ flag.BoolVar(&opts.load, "load", false, "Load-harness mode: one attributable event shape, a run id in every title, and a JSON summary")
+ flag.StringVar(&opts.runID, "run-id", "", "Load mode: run identifier stamped into every title (default: generated)")
+ flag.Int64Var(&opts.total, "total", 0, "Load mode: stop after this many events (0 = until --duration elapses)")
+ flag.IntVar(&opts.workers, "workers", 8, "Load mode: concurrent senders")
+ flag.IntVar(&opts.targetEPS, "target-eps", 0, "Load mode: pace to this many events per second (0 = saturate)")
+ flag.StringVar(&opts.summary, "summary", "", "Load mode: write the run summary as JSON to this path")
flag.Parse()
- fmt.Printf("[demo-producer] ingest=%s tenant=%s rate=%d batch=%d connectors=%d\n",
- opts.ingestURL, opts.tenant, opts.rate, opts.batch, len(profiles))
-
ctx, cancel := context.WithCancel(context.Background())
if opts.duration > 0 {
ctx, cancel = context.WithTimeout(ctx, opts.duration)
@@ -299,14 +597,22 @@ func main() {
cancel()
}()
- var sent atomic.Int64
+ if opts.load {
+ os.Exit(mainLoad(ctx, opts))
+ }
+
+ fmt.Printf("[demo-producer] ingest=%s tenant=%s rate=%d batch=%d connectors=%d\n",
+ opts.ingestURL, opts.tenant, opts.rate, opts.batch, len(profiles))
+
+ st := newStats()
var wg sync.WaitGroup
for _, p := range profiles {
wg.Add(1)
- go runProducer(ctx, &wg, p, opts, &sent)
+ go runProducer(ctx, &wg, p, opts, st)
}
- // Periodic stats line.
+ // Periodic stats line. Accepted, not attempted: a stack refusing every
+ // batch must not read as one taking them.
go func() {
t := time.NewTicker(5 * time.Second)
defer t.Stop()
@@ -315,13 +621,60 @@ func main() {
case <-ctx.Done():
return
case <-t.C:
- fmt.Printf("[demo-producer] events sent so far: %d\n", sent.Load())
+ fmt.Printf("[demo-producer] events accepted so far: %d (attempted %d)\n",
+ st.accepted.Load(), st.attempted.Load())
}
}
}()
wg.Wait()
- fmt.Printf("[demo-producer] done. total events sent: %d\n", sent.Load())
+ fmt.Printf("[demo-producer] done. accepted %d of %d attempted\n", st.accepted.Load(), st.attempted.Load())
+}
+
+func mainLoad(ctx context.Context, opts options) int {
+ if opts.runID == "" {
+ opts.runID = fmt.Sprintf("%x", time.Now().UnixNano())[:10]
+ }
+ if opts.workers < 1 {
+ opts.workers = 1
+ }
+ if opts.batch < 1 {
+ opts.batch = 1
+ }
+ if opts.total <= 0 && opts.duration <= 0 {
+ fmt.Fprintln(os.Stderr, "[load] refusing to run unbounded: pass --total or --duration")
+ return 2
+ }
+ fmt.Fprintf(os.Stderr, "[load] run=%s ingest=%s total=%d workers=%d batch=%d target-eps=%d\n",
+ opts.runID, opts.ingestURL, opts.total, opts.workers, opts.batch, opts.targetEPS)
+
+ summary := runLoad(ctx, opts)
+
+ if opts.summary != "" {
+ if err := writeSummary(opts.summary, summary); err != nil {
+ fmt.Fprintf(os.Stderr, "[load] could not write %s: %v\n", opts.summary, err)
+ return 1
+ }
+ }
+ blob, _ := json.MarshalIndent(summary, "", " ")
+ fmt.Println(string(blob))
+
+ codes := make([]string, 0, len(summary.StatusCounts))
+ for code := range summary.StatusCounts {
+ codes = append(codes, code)
+ }
+ sort.Strings(codes)
+ fmt.Fprintf(os.Stderr, "[load] accepted %d of %d attempted in %.1fs (%.0f eps); statuses %v\n",
+ summary.Accepted, summary.Attempted, summary.WallSeconds, summary.AcceptedEPS, codes)
+
+ // A run that accepted nothing is a failed run, not a run that measured
+ // zero throughput. Saying so here stops a harness publishing an honest
+ // zero for what was actually a misconfiguration.
+ if summary.Accepted == 0 {
+ fmt.Fprintln(os.Stderr, "[load] ingest accepted no events; check --token and --ingest-url")
+ return 1
+ }
+ return 0
}
func envDefault(key, fallback string) string {
diff --git a/tests/test_load_harness_contract.py b/tests/test_load_harness_contract.py
new file mode 100644
index 000000000..8501e1884
--- /dev/null
+++ b/tests/test_load_harness_contract.py
@@ -0,0 +1,134 @@
+"""The load harness and the producer have to agree, and neither may publish an absence as a number.
+
+Two contracts are pinned here.
+
+**The marker.** ``services/demo-producer`` stamps a run id and a sequence
+number into every event title; ``scripts/perf/load_harness.py`` matches alert
+rows on that string. If the two spellings drift apart, the harness correlates
+nothing and reports that every event was lost. A throughput regression and a
+pipeline outage look identical from the outside, and the real cause is a
+renamed constant. The Go constant is read out of the source rather than
+re-declared here, so this test runs in the direction that actually drifts.
+
+**The zero.** The repository's rule is that a figure which was not measured
+reads "not measured", never ``0``. The harness encodes that as a type; this
+asserts the serialised form, because that is what a renderer downstream sees.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def _load(module_name: str, relative: str):
+ path = ROOT / relative
+ sys.path.insert(0, str(path.parent))
+ spec = importlib.util.spec_from_file_location(module_name, path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ # Registered before exec: @dataclass resolves annotations through
+ # sys.modules[cls.__module__], and an unregistered module makes that None.
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+harness = _load("aisoc_load_harness", "scripts/perf/load_harness.py")
+
+
+def test_marker_matches_the_producer_that_writes_it() -> None:
+ source = (ROOT / "services" / "demo-producer" / "main.go").read_text(encoding="utf-8")
+ declared = re.search(r'const MarkerPrefix = "([^"]+)"', source)
+ assert declared, "services/demo-producer no longer declares MarkerPrefix"
+ assert declared.group(1) == harness.MARKER_PREFIX, (
+ "the producer stamps a different marker than the harness matches on, so every run would report total loss"
+ )
+
+
+def test_the_title_the_producer_formats_is_the_title_the_harness_parses() -> None:
+ source = (ROOT / "services" / "demo-producer" / "main.go").read_text(encoding="utf-8")
+ # The Go format string, turned into one concrete title. Taking it from the
+ # source rather than hand-copying it is the point: a reordered field or a
+ # changed separator has to fail here.
+ fmt = re.search(r'"title":\s*fmt\.Sprintf\("([^"]+)"', source)
+ assert fmt, "the load event no longer formats its title with a recognisable Sprintf"
+ concrete = (
+ fmt.group(1).replace("%s %s", f"{harness.MARKER_PREFIX} run1", 1).replace("%d", "7", 1).replace("%d", "1700000000123456789", 1)
+ )
+ match = harness._TITLE_RE.match(concrete)
+ assert match, f"the harness cannot parse a title the producer would write: {concrete!r}"
+ assert match.group("run") == "run1"
+ assert match.group("seq") == "7"
+ assert match.group("sent") == "1700000000123456789"
+
+
+def _empty_report() -> dict:
+ return harness.build_report(
+ target=harness.Target(name="t", psql=[], kafka=[], stats=None, ingest_url=""),
+ summary=harness.ProducerSummary(
+ {"run_id": "x", "attempted_events": 10, "accepted_events": 0, "wall_seconds": 1.0, "accepted_eps": 0.0}
+ ),
+ alerts=[],
+ clock_offset=0.0,
+ clock_spread=0.0,
+ lag_in_flight=(None, "broker unreachable"),
+ lag_drained=(None, "broker unreachable"),
+ dead_letters=None,
+ dead_letter_reason="table unreadable",
+ resources=[],
+ drain_seconds=0.0,
+ settled=False,
+ )
+
+
+def test_a_metric_that_was_not_measured_serialises_without_a_value(_empty_report: dict) -> None:
+ for name, body in _empty_report["metrics"].items():
+ assert body["measured"] is False, name
+ assert "value" not in body, f"{name} would render as a number nobody measured"
+ assert body["reason"], f"{name} does not say why it was not measured"
+
+
+def test_a_measured_zero_is_still_a_zero() -> None:
+ report = harness.build_report(
+ target=harness.Target(name="t", psql=[], kafka=[], stats=None, ingest_url=""),
+ summary=harness.ProducerSummary(
+ {"run_id": "x", "attempted_events": 2, "accepted_events": 2, "wall_seconds": 1.0, "accepted_eps": 2.0}
+ ),
+ alerts=[harness.AlertRow(seq=0, sent_epoch=1.0, created_epoch=1.1), harness.AlertRow(seq=1, sent_epoch=1.0, created_epoch=1.2)],
+ clock_offset=0.0,
+ clock_spread=0.0,
+ lag_in_flight=(0, ""),
+ lag_drained=(0, ""),
+ dead_letters=0,
+ dead_letter_reason="",
+ resources=[],
+ drain_seconds=0.0,
+ settled=True,
+ )
+ lag = report["metrics"]["consumer_lag_drained"]
+ assert lag["measured"] is True and lag["value"] == 0.0, (
+ "a drained queue really is zero; collapsing it into 'not measured' would hide a working pipeline"
+ )
+ assert report["metrics"]["dead_letter_rate"]["value"] == 0.0
+
+
+def test_every_published_result_declares_it_is_not_an_slo() -> None:
+ import json
+
+ results = sorted((ROOT / "docs" / "perf" / "results").glob("*.json"))
+ assert results, "no published results; the performance page would be quoting nothing"
+ perf = [json.loads(p.read_text(encoding="utf-8")) for p in results]
+ perf = [b for b in perf if str(b.get("schema", "")).startswith("aisoc.load_harness")]
+ assert perf, "no load-harness results among the published files"
+ for blob in perf:
+ assert blob["not_a_production_slo"] is True
+ assert blob["slo_disclaimer"].strip()
+ assert blob["hardware"].get("cpu") or blob["hardware"].get("ci_runner")