Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

docs(recipes): continuous anomaly datafeed recipe + guide

xerj-orgac041c29af94
diff --git a/docs/examples/continuous-anomaly-datafeeds/datafeed_demo.py b/docs/examples/continuous-anomaly-datafeeds/datafeed_demo.py
new file mode 100644
index 000000000..e6487388a
--- /dev/null
+++ b/docs/examples/continuous-anomaly-datafeeds/datafeed_demo.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+"""
+Continuous anomaly detection with an XERJ _ml datafeed.
+
+The on-demand `_score` API scores a series once, on request. A *datafeed* turns
+that into a live monitor: it references a detector, and once started it re-scores
+the source index every `frequency`, appending only the NEW flagged buckets to the
+job's results store — which you poll with
+`GET /_ml/anomaly_detectors/{job}/results/records`. Same transparent moving
+mean/stddev z-score, now on a timer.
+
+This demo proves the "continuous" part end to end:
+ 1. ingest a metric series with one spike, create a detector + datafeed,
+ 2. _start it (one scoring pass runs immediately) and read the first anomaly,
+ 3. ingest a SECOND spike into the live index,
+ 4. poll until the background scorer picks it up — with no second _start.
+
+Run: python3 datafeed_demo.py # assumes XERJ on :9486
+ XERJ=http://localhost:9200 python3 datafeed_demo.py
+
+Uses only the Python 3 standard library. No pip installs.
+"""
+
+import datetime
+import os
+import sys
+import time
+import json
+import urllib.error
+import urllib.request
+
+XERJ = os.environ.get("XERJ", "http://localhost:9486").rstrip("/")
+INDEX = "cpu_datafeed"
+DETECTOR = "cpu-spike"
+DATAFEED = "cpu-spike-feed"
+FREQUENCY = "2s" # re-score cadence for the background scorer
+
+
+def call(method, path, body=None):
+ data = None
+ headers = {}
+ if body is not None:
+ data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
+ headers["Content-Type"] = (
+ "application/x-ndjson" if isinstance(body, str) else "application/json"
+ )
+ req = urllib.request.Request(f"{XERJ}{path}", data=data, headers=headers, method=method)
+ with urllib.request.urlopen(req) as resp:
+ return json.loads(resp.read())
+
+
+def ingest(readings):
+ """Ingest [(minute, cpu)] as one doc per minute (one reading per bucket)."""
+ lines = []
+ for minute, cpu in readings:
+ ts = "2026-07-06T00:%02d:00Z" % minute
+ lines.append(json.dumps({"index": {"_index": INDEX}}))
+ lines.append(json.dumps({"@timestamp": ts, "cpu": cpu}))
+ call("POST", "/_bulk?refresh=true", "\n".join(lines) + "\n")
+
+
+def when(record):
+ ts = datetime.datetime.fromtimestamp(record["timestamp"] / 1000, datetime.timezone.utc)
+ return ts.strftime("%Y-%m-%d %H:%M UTC")
+
+
+def show(records):
+ print(" when actual expected record_score")
+ for r in sorted(records, key=lambda r: r["timestamp"]):
+ print(" %-20s %8.1f %10.1f %14.1f"
+ % (when(r), r["actual"], r["expected"], r["record_score"]))
+
+
+def poll_records(min_count, timeout_s=15):
+ """Poll results/records until at least `min_count` are stored (or time out)."""
+ deadline = time.time() + timeout_s
+ while time.time() < deadline:
+ recs = call("GET", f"/_ml/anomaly_detectors/{DETECTOR}/results/records")["records"]
+ if len(recs) >= min_count:
+ return recs
+ time.sleep(1)
+ return call("GET", f"/_ml/anomaly_detectors/{DETECTOR}/results/records")["records"]
+
+
+def main():
+ # Fresh index: @timestamp (bucketing clock) + cpu (the metric we average).
+ try:
+ call("DELETE", f"/{INDEX}")
+ except urllib.error.HTTPError:
+ pass
+ call("PUT", f"/{INDEX}", {
+ "mappings": {"properties": {
+ "@timestamp": {"type": "date"},
+ "cpu": {"type": "double"},
+ }}
+ })
+
+ # Baseline ~20% CPU for 16 minutes, with a runaway spike to 96 at minute 12.
+ baseline = [19, 21, 20, 20, 22, 18, 21, 20, 19, 21, 20, 22, 96, 20, 21, 19]
+ ingest(list(enumerate(baseline)))
+
+ # A detector is which index, which clock field, what metric, bucket size,
+ # and how many stddevs count as anomalous.
+ call("PUT", f"/_ml/anomaly_detectors/{DETECTOR}", {
+ "source_index": INDEX,
+ "time_field": "@timestamp",
+ "function": "mean",
+ "field": "cpu",
+ "bucket_span": "1m",
+ "anomaly_threshold": 3.0,
+ "description": "per-minute CPU mean vs moving baseline",
+ })
+
+ # A datafeed points a detector at a live index and runs it on a timer.
+ feed = call("PUT", f"/_ml/datafeeds/{DATAFEED}", {
+ "job_id": DETECTOR,
+ "frequency": FREQUENCY,
+ })
+ print(f"datafeed {feed['datafeed_id']} -> job {feed['job_id']} "
+ f"(every {feed['frequency']}), state={feed['state']}\n")
+
+ # Start it: one scoring pass runs synchronously now, then a background task
+ # re-scores every `frequency`.
+ call("POST", f"/_ml/datafeeds/{DATAFEED}/_start")
+ first = poll_records(1)
+ print(f"after _start — {len(first)} anomaly record(s) from the first pass:")
+ show(first)
+
+ # Now the "continuous" part: a NEW spike lands in the live index at minute
+ # 20. We do NOT touch the datafeed — the running background scorer should
+ # find it on its next tick.
+ print(f"\ninjecting a new spike at 00:20, waiting for the {FREQUENCY} scorer...")
+ ingest([(16, 20), (17, 21), (18, 19), (19, 20), (20, 88), (21, 20)])
+ after = poll_records(len(first) + 1)
+ new = [r for r in after if r not in first]
+ print(f"datafeed picked up {len(new)} new anomaly record(s) on its own:")
+ show(new)
+
+ # Stop the datafeed (idempotent cleanup for re-runs).
+ stopped = call("POST", f"/_ml/datafeeds/{DATAFEED}/_stop")
+ fed = call("GET", f"/_ml/datafeeds/{DATAFEED}")["datafeeds"][0]
+ print(f"\n_stop -> {stopped} · datafeed state now: {fed['state']}")
+
+ # Verify: both spikes were detected, the second WITHOUT re-starting.
+ spikes = {when(r): r["actual"] for r in after}
+ assert any(96.0 == v for v in spikes.values()), "first spike (00:12) missing"
+ assert any(88.0 == v for v in spikes.values()), "continuously-detected spike (00:20) missing"
+ assert len(after) >= 2, f"expected >=2 anomaly records, got {len(after)}"
+ assert fed["state"] == "stopped", "datafeed did not stop"
+ print(f"\nOK: {len(after)} anomalies detected continuously; datafeed stopped cleanly.")
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except AssertionError as e:
+ print(f"FAILED: {e}", file=sys.stderr)
+ sys.exit(1)
diff --git a/docs/recipes/README.md b/docs/recipes/README.md
index 636329af8..186def22a 100644
--- a/docs/recipes/README.md
+++ b/docs/recipes/README.md
@@ -13,6 +13,7 @@ These are practical "how do I actually do X" recipes, not an API reference (that
| [Vector quantization](./vector-quantization.md) | Opt a `dense_vector` field into scalar8 (`int8_hnsw`) — 4× smaller vectors, recall@10 ≈ 0.99 | [`quant_demo.py`](../examples/vector-quantization/quant_demo.py) |
| [Hybrid search](./hybrid-search.md) | Keyword + vector in one query — results neither BM25 nor kNN finds alone | [`hybrid_search.py`](../examples/hybrid-search/hybrid_search.py) |
| [Anomaly detection](./anomaly-detection.md) | Statistical `_ml` detectors that flag spikes in metrics/logs | [`anomaly_detection.py`](../examples/anomaly-detection/anomaly_detection.py) |
+| [Continuous anomaly datafeeds](./continuous-anomaly-datafeeds.md) | A live `_ml` datafeed that re-scores an index on a timer and stores new anomaly records you poll | [`datafeed_demo.py`](../examples/continuous-anomaly-datafeeds/datafeed_demo.py) |
| [Migrate from Elasticsearch](./migrate-from-elasticsearch.md) | Point your existing ES client at XERJ — same wire, change the URL | [`migrate_demo.sh`](../examples/migrate-from-elasticsearch/migrate_demo.sh) |
Every example is stdlib-only Python 3 or plain `curl` — no dependencies to install. Start XERJ (`./target/release/xerj --data-dir ./data --insecure`), then run any example.
diff --git a/docs/recipes/continuous-anomaly-datafeeds.md b/docs/recipes/continuous-anomaly-datafeeds.md
new file mode 100644
index 000000000..e62b8a3f8
--- /dev/null
+++ b/docs/recipes/continuous-anomaly-datafeeds.md
@@ -0,0 +1,235 @@
+# Monitor a metric continuously with a datafeed
+
+**Goal:** you already know how to score a metric series for anomalies on demand
+(see [Detect a spike in a metric series](./anomaly-detection.md) — you POST
+`_score` and get the whole timeline back). But a dashboard or an alerting loop
+doesn't want to *ask* every time; it wants the engine to keep watching a live
+index and hand you new anomalies as they appear. That's a **datafeed**.
+
+XERJ ships the Elasticsearch `_ml/datafeeds` surface. A datafeed references an
+existing anomaly-detection job (a detector), reads from one or more `indices`
+through an optional `query`, and runs on a fixed `frequency`. When you `_start`
+it, XERJ scores the series once immediately and then keeps re-scoring on a timer,
+appending only the **newly** flagged buckets to the job's results — which you
+read back with `GET /_ml/anomaly_detectors/{job}/results/records`. Same
+transparent moving mean/stddev z-score as the on-demand path; now it runs
+itself.
+
+> **Honest scope.** The scoring is the same deterministic moving-window z-score
+> as `_score` — a great fit for "this metric jumped relative to its recent
+> self," not a seasonal/multivariate model. Results are held **in memory**
+> (bounded to the last ~10k records per job) and the background scorer is a
+> per-node **tokio task**: results and running datafeeds do **not** survive a
+> restart (a reloaded datafeed comes back `stopped`, and `_start` begins a fresh
+> run). This is single-node — there is no cross-node datafeed scheduler. It is
+> exactly what you want for a live dashboard or a self-contained alert loop on
+> one node; it is not a replacement for a clustered, durable ML pipeline.
+
+## The scenario
+
+`cpu_datafeed` collects one CPU reading per minute. For sixteen minutes it sits
+around 20%, with a runaway spike to **96%** at minute 12. We create a detector,
+attach a datafeed, and start it. Then — while the datafeed is running — a
+**second** spike (88%) lands at minute 20, and we watch the datafeed find it on
+its own.
+
+## 1. Map the index and create the detector
+
+The time field must be a `date`; the metric must be numeric. The detector is the
+same object as in the on-demand recipe: `mean(cpu)` over one-minute buckets.
+
+```bash
+curl -XPUT localhost:9486/cpu_datafeed -H 'Content-Type: application/json' -d '{
+ "mappings": { "properties": {
+ "@timestamp": { "type": "date" },
+ "cpu": { "type": "double" }
+ }}
+}'
+
+curl -XPUT localhost:9486/_ml/anomaly_detectors/cpu-spike \
+ -H 'Content-Type: application/json' -d '{
+ "source_index": "cpu_datafeed",
+ "time_field": "@timestamp",
+ "function": "mean",
+ "field": "cpu",
+ "bucket_span": "1m"
+ }'
+```
+
+## 2. Create the datafeed
+
+A datafeed needs a `job_id` (which must reference an existing detector — else
+`404`). `indices` defaults to the detector's `source_index`, `query` to
+`match_all`, and `frequency` parses an ES time value (`"2s"`, `"5m"`, …; clamped
+to `>= 1s`, default `60s`).
+
+```bash
+curl -XPUT localhost:9486/_ml/datafeeds/cpu-spike-feed \
+ -H 'Content-Type: application/json' -d '{
+ "job_id": "cpu-spike",
+ "frequency": "2s"
+ }'
+```
+
+Response (the datafeed config, ES-shaped):
+
+```json
+{
+ "datafeed_id": "cpu-spike-feed",
+ "job_id": "cpu-spike",
+ "state": "stopped",
+ "indices": ["cpu_datafeed"],
+ "query": { "match_all": {} },
+ "frequency": "2s"
+}
+```
+
+## 3. Start it — one pass now, then a timer
+
+`_start` marks the datafeed `started`, runs **one scoring pass synchronously**
+(so results are immediately queryable), and spawns a background task that
+re-scores every `frequency`.
+
+```bash
+curl -XPOST localhost:9486/_ml/datafeeds/cpu-spike-feed/_start
+# -> {"started": true}
+```
+
+Read the results the first pass produced:
+
+```bash
+curl 'localhost:9486/_ml/anomaly_detectors/cpu-spike/results/records'
+```
+
+```json
+{
+ "count": 1,
+ "records": [
+ {
+ "job_id": "cpu-spike",
+ "timestamp": 1783296720000,
+ "timestamp_iso": "2026-07-06T00:12:00.000Z",
+ "actual": 96.0,
+ "typical": 20.25,
+ "expected": 20.25,
+ "std_dev": 1.1636866703140785,
+ "z_score": 65.09484205018445,
+ "record_score": 100.0,
+ "bucket_span": "1m",
+ "is_anomaly": true
+ }
+ ]
+}
+```
+
+Each record reuses the fields the `_score` endpoint emits per bucket, plus the
+ES `record_score` (the 0–100 severity) and `typical` (ES's name for the
+baseline `expected`).
+
+## 4. The continuous part
+
+Now push a **new** spike into the live index — without touching the datafeed:
+
+```bash
+curl -XPOST 'localhost:9486/_bulk?refresh=true' \
+ -H 'Content-Type: application/x-ndjson' --data-binary $'
+{"index":{"_index":"cpu_datafeed"}}
+{"@timestamp":"2026-07-06T00:20:00Z","cpu":88}
+'
+```
+
+Within one `frequency` tick the background scorer re-buckets the series, sees the
+new bucket, and appends it. Poll again a couple of seconds later:
+
+```bash
+curl 'localhost:9486/_ml/anomaly_detectors/cpu-spike/results/records'
+# -> count: 2 (the 00:12 spike AND the new 00:20 spike)
+```
+
+The datafeed tracks the highest bucket timestamp it has already scored, so each
+pass appends only the **new** anomalies — the 00:12 record is never duplicated.
+
+> **A note on freshness.** XERJ's read path caches aggregation results keyed by
+> `(query, dataset_version)`, and version only bumps on a segment flush — so an
+> *identical* query repeated against an index that has only taken unflushed
+> (in-memory) writes can be served a cached result. Because a datafeed re-issues
+> the same query every tick, its scorer deliberately requests an **uncached**
+> read so it always sees the newest buckets. (The on-demand `_score` endpoint is
+> unchanged and remains cache-eligible.)
+
+## 5. Filter and cap the results
+
+`results/records` accepts a `record_score` floor (query param or JSON body) and a
+`size` cap:
+
+```bash
+# only high-severity records
+curl 'localhost:9486/_ml/anomaly_detectors/cpu-spike/results/records?record_score=90'
+# at most 5, most-recent-friendly (chronological)
+curl 'localhost:9486/_ml/anomaly_detectors/cpu-spike/results/records?size=5'
+```
+
+## 6. Stop and delete
+
+```bash
+curl -XPOST localhost:9486/_ml/datafeeds/cpu-spike-feed/_stop
+# -> {"stopped": true} (aborts the background task)
+
+curl localhost:9486/_cat/ml/datafeeds
+# cpu-spike-feed stopped cpu-spike
+
+curl -XDELETE localhost:9486/_ml/datafeeds/cpu-spike-feed
+# {"acknowledged": true}
+```
+
+A datafeed must be stopped before it can be deleted — deleting a `started`
+datafeed returns `409`, exactly like Elasticsearch.
+
+## Run it
+
+```bash
+# XERJ listening on :9486 (adjust XERJ=... for another port)
+python3 docs/examples/continuous-anomaly-datafeeds/datafeed_demo.py
+```
+
+The script maps the index, ingests the series with the first spike, creates the
+detector and datafeed, starts it, reads the first anomaly, injects the second
+spike into the live index, polls until the running datafeed picks it up on its
+own, then stops and **asserts** both spikes were detected — the second without a
+second `_start`. It exits non-zero if any of that regresses, so it doubles as a
+smoke test.
+
+Expected output:
+
+```
+datafeed cpu-spike-feed -> job cpu-spike (every 2s), state=stopped
+
+after _start — 1 anomaly record(s) from the first pass:
+ when actual expected record_score
+ 2026-07-06 00:12 UTC 96.0 20.2 100.0
+
+injecting a new spike at 00:20, waiting for the 2s scorer...
+datafeed picked up 1 new anomaly record(s) on its own:
+ when actual expected record_score
+ 2026-07-06 00:20 UTC 88.0 20.2 100.0
+
+_stop -> {'stopped': True} · datafeed state now: stopped
+
+OK: 2 anomalies detected continuously; datafeed stopped cleanly.
+```
+
+## Endpoint cheat-sheet
+
+| Method | Path | Purpose |
+|---|---|---|
+| `PUT` | `/_ml/datafeeds/{id}` | create/replace a datafeed (`job_id` required; `indices`, `query`, `frequency` optional) |
+| `GET` | `/_ml/datafeeds/{id}` | fetch one datafeed |
+| `GET` | `/_ml/datafeeds` | list all datafeeds (`{datafeeds, count}`) |
+| `DELETE` | `/_ml/datafeeds/{id}` | remove a datafeed (must be stopped, else `409`) |
+| `POST` | `/_ml/datafeeds/{id}/_start` | start: score now + re-score every `frequency` |
+| `POST` | `/_ml/datafeeds/{id}/_stop` | stop and abort the background scorer |
+| `GET` | `/_ml/anomaly_detectors/{job}/results/records` | stored anomaly records; `record_score` / `size` filters |
+| `GET` | `/_cat/ml/datafeeds` | one line per datafeed: `id state job_id` |
+
+See [Detect a spike in a metric series](./anomaly-detection.md) for the detector
+model and the scoring math these records come from.
diff --git a/recipes/README.md b/recipes/README.md
index 946324d73..051819957 100644
--- a/recipes/README.md
+++ b/recipes/README.md
@@ -26,6 +26,7 @@ python3 recipes/semantic_search.py
python3 recipes/rag_app.py
python3 recipes/memory_agent.py # run twice — memory persists
python3 recipes/log_anomaly.py
+python3 recipes/anomaly_datafeed.py
python3 recipes/vector_quantization.py
```
@@ -39,6 +40,7 @@ Every recipe honors `XERJ_URL` (default `http://localhost:9200`).
| [`rag_app.py`](rag_app.py) | A full RAG pipeline: HTML→text→chunk→index→hybrid-retrieve→answer, with a retrieval eval and citations | XERJ's own docs (`landing/docs/*.html`) — ~96 chunks over 23 pages |
| [`memory_agent.py`](memory_agent.py) | A triage agent with **persistent** long-term memory via the `/_memory` API: recall similar past incidents, decide, remember | Real OpenSSH attack capture (`engine/demo-data/ssh_one.ndjson`, logpai/loghub) |
| [`log_anomaly.py`](log_anomaly.py) | Statistical anomaly detection (`_ml`) finding brute-force spikes over a moving baseline, then attributing the worst hour | Same real SSH capture (655k events) |
+| [`anomaly_datafeed.py`](anomaly_datafeed.py) | A **continuous** `_ml` datafeed: start it once, then a background scorer re-buckets the live index every few seconds and appends new anomaly records you poll — a second spike is detected with no second call | Synthetic per-minute CPU series with two injected spikes |
## What each one exercises in the engine
@@ -50,6 +52,9 @@ Every recipe honors `XERJ_URL` (default `http://localhost:9200`).
real per-namespace index, so memory survives restarts.
- **`_ml` anomaly detection** — `PUT /_ml/anomaly_detectors/{id}` +
`_score`: date-histogram buckets scored against a moving mean/stddev.
+- **`_ml` continuous datafeeds** — `PUT /_ml/datafeeds/{id}` + `_start`/`_stop`
+ and `GET /_ml/anomaly_detectors/{job}/results/records`: a background task
+ re-scores a live index on a timer and stores newly-flagged buckets.
- **ordinary ES aggregations** — `terms`/`range` used alongside the AI
features (attribution in the anomaly recipe).
diff --git a/recipes/anomaly_datafeed.py b/recipes/anomaly_datafeed.py
new file mode 100644
index 000000000..2d4a7d97a
--- /dev/null
+++ b/recipes/anomaly_datafeed.py
@@ -0,0 +1,159 @@
+#!/usr/bin/env python3
+"""Continuously detect anomalies with an XERJ _ml datafeed.
+
+The on-demand `_score` API (see recipes/log_anomaly.py) scores a series once,
+on request. A *datafeed* turns that into a live monitor: it references a
+detector, and once started it re-scores the source index every `frequency`,
+appending only the NEW flagged buckets to the job's results store — which you
+poll with `GET /_ml/anomaly_detectors/{job}/results/records`. Same transparent
+moving mean/stddev z-score, now running on a timer.
+
+This recipe proves the "continuous" part end to end:
+ 1. ingest a metric series with one spike, create a detector + datafeed,
+ 2. _start it (one scoring pass runs immediately) and read the first anomaly,
+ 3. ingest a SECOND spike into the live index,
+ 4. poll until the background scorer picks it up — with no second _start.
+
+Run it:
+ xerj --insecure --data-dir ./data & # start XERJ
+ python3 recipes/anomaly_datafeed.py
+
+Optional env:
+ XERJ_URL (default http://localhost:9200)
+"""
+
+import datetime
+import json
+import os
+import sys
+import time
+import urllib.error
+import urllib.request
+
+XERJ = os.environ.get("XERJ_URL", "http://localhost:9200").rstrip("/")
+INDEX = "cpu_datafeed"
+DETECTOR = "cpu-spike"
+DATAFEED = "cpu-spike-feed"
+FREQUENCY = "2s" # re-score cadence for the background scorer
+
+
+def call(method, path, body=None):
+ data = None
+ headers = {}
+ if body is not None:
+ data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
+ headers["Content-Type"] = (
+ "application/x-ndjson" if isinstance(body, str) else "application/json"
+ )
+ req = urllib.request.Request(f"{XERJ}{path}", data=data, headers=headers, method=method)
+ with urllib.request.urlopen(req) as resp:
+ return json.loads(resp.read())
+
+
+def ingest(readings):
+ """Ingest [(minute, cpu)] as one doc per minute (one reading per bucket)."""
+ lines = []
+ for minute, cpu in readings:
+ ts = "2026-07-06T00:%02d:00Z" % minute
+ lines.append(json.dumps({"index": {"_index": INDEX}}))
+ lines.append(json.dumps({"@timestamp": ts, "cpu": cpu}))
+ call("POST", "/_bulk?refresh=true", "\n".join(lines) + "\n")
+
+
+def when(record):
+ ts = datetime.datetime.fromtimestamp(record["timestamp"] / 1000, datetime.timezone.utc)
+ return ts.strftime("%Y-%m-%d %H:%M UTC")
+
+
+def show(records):
+ print(" when actual expected record_score")
+ for r in sorted(records, key=lambda r: r["timestamp"]):
+ print(" %-20s %8.1f %10.1f %14.1f"
+ % (when(r), r["actual"], r["expected"], r["record_score"]))
+
+
+def poll_records(min_count, timeout_s=15):
+ """Poll results/records until at least `min_count` are stored (or time out)."""
+ deadline = time.time() + timeout_s
+ while time.time() < deadline:
+ recs = call("GET", f"/_ml/anomaly_detectors/{DETECTOR}/results/records")["records"]
+ if len(recs) >= min_count:
+ return recs
+ time.sleep(1)
+ return call("GET", f"/_ml/anomaly_detectors/{DETECTOR}/results/records")["records"]
+
+
+def main():
+ # Fresh index: @timestamp (bucketing clock) + cpu (the metric we average).
+ try:
+ call("DELETE", f"/{INDEX}")
+ except urllib.error.HTTPError:
+ pass
+ call("PUT", f"/{INDEX}", {
+ "mappings": {"properties": {
+ "@timestamp": {"type": "date"},
+ "cpu": {"type": "double"},
+ }}
+ })
+
+ # Baseline ~20% CPU for 16 minutes, with a runaway spike to 96 at minute 12.
+ baseline = [19, 21, 20, 20, 22, 18, 21, 20, 19, 21, 20, 22, 96, 20, 21, 19]
+ ingest(list(enumerate(baseline)))
+
+ # A detector is which index, which clock field, what metric, bucket size,
+ # and how many stddevs count as anomalous.
+ call("PUT", f"/_ml/anomaly_detectors/{DETECTOR}", {
+ "source_index": INDEX,
+ "time_field": "@timestamp",
+ "function": "mean",
+ "field": "cpu",
+ "bucket_span": "1m",
+ "anomaly_threshold": 3.0,
+ "description": "per-minute CPU mean vs moving baseline",
+ })
+
+ # A datafeed points a detector at a live index and runs it on a timer.
+ feed = call("PUT", f"/_ml/datafeeds/{DATAFEED}", {
+ "job_id": DETECTOR,
+ "frequency": FREQUENCY,
+ })
+ print(f"datafeed {feed['datafeed_id']} -> job {feed['job_id']} "
+ f"(every {feed['frequency']}), state={feed['state']}\n")
+
+ # Start it: one scoring pass runs synchronously now, then a background task
+ # re-scores every `frequency`.
+ call("POST", f"/_ml/datafeeds/{DATAFEED}/_start")
+ first = poll_records(1)
+ print(f"after _start — {len(first)} anomaly record(s) from the first pass:")
+ show(first)
+
+ # Now the "continuous" part: a NEW spike lands in the live index at minute
+ # 20. We do NOT touch the datafeed — the running background scorer should
+ # find it on its next tick.
+ print(f"\ninjecting a new spike at 00:20, waiting for the {FREQUENCY} scorer...")
+ ingest([(16, 20), (17, 21), (18, 19), (19, 20), (20, 88), (21, 20)])
+ after = poll_records(len(first) + 1)
+ new = [r for r in after if r not in first]
+ print(f"datafeed picked up {len(new)} new anomaly record(s) on its own:")
+ show(new)
+
+ # Stop the datafeed (idempotent cleanup for re-runs).
+ stopped = call("POST", f"/_ml/datafeeds/{DATAFEED}/_stop")
+ fed = call("GET", f"/_ml/datafeeds/{DATAFEED}")["datafeeds"][0]
+ print(f"\n_stop -> {stopped} · datafeed state now: {fed['state']}")
+
+ # Verify: both spikes were detected, the second WITHOUT re-starting.
+ spikes = {when(r): r["actual"] for r in after}
+ assert any(96.0 == v for v in spikes.values()), "first spike (00:12) missing"
+ assert any(88.0 == v for v in spikes.values()), "continuously-detected spike (00:20) missing"
+ assert len(after) >= 2, f"expected >=2 anomaly records, got {len(after)}"
+ assert fed["state"] == "stopped", "datafeed did not stop"
+ print(f"\nOK: {len(after)} anomalies detected continuously; datafeed stopped cleanly.")
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except AssertionError as e:
+ print(f"FAILED: {e}", file=sys.stderr)
+ sys.exit(1)
diff --git a/recipes/run_all.sh b/recipes/run_all.sh
index 5fb9d0aca..154e51be5 100755
--- a/recipes/run_all.sh
+++ b/recipes/run_all.sh
@@ -35,7 +35,7 @@ until curl -fsS "$XERJ_URL/" >/dev/null 2>&1; do
done
rc=0
-for r in semantic_search rag_app memory_agent log_anomaly vector_quantization; do
+for r in semantic_search rag_app memory_agent log_anomaly anomaly_datafeed vector_quantization; do
printf '\n═══ %s ═══\n' "$r"
if python3 "$ROOT/recipes/$r.py"; then :; else echo "FAILED: $r"; rc=1; fi
done