Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,33 @@ The detector is deliberately conservative: a single noisy sample should never pa
- **What it costs.** Detection needs at least two samples, so time to detect is at least one sample interval after the first anomalous sample. In six local runs of the guided demo the leak was detected 2 to 4 s after it was injected and resolved 10 to 13 s after detection (release, then three normal samples). These are demo measurements on a laptop, not production numbers.
- **What it misses.** Leaks smaller than 30 MB, CPU bursts shorter than two samples, and anything that is not CPU or memory. Database corruption is caught by a query, not by the model.

## Reliability benchmark

Run on 2026-11-10. This is the larger, reproducible complement to the six local demo runs above: a deterministic simulation of the real `Detector` (real config constants, fake clock, seeded RNG, no threads or network) on synthetic sample streams. It is **not production telemetry**, and "closed" measures the detector noticing normal samples again, not a real process recovering.

Command: `.venv/Scripts/python target_app/benchmark_detection.py` (flags `-m`, `-n` and `--minutes` change the sample sizes; the defaults are small so a full run takes about 70 s, because the Isolation Forest is refitted for every candidate sample).

| Runs | Simulated hours | False incidents | Incidents per hour | Runs with a false incident |
|---|---|---|---|---|
| 20 | 3.3 | 0 | 0.000 | 0.0% |

| Fault | Runs | Detected within 60 s | Detect p50 | Detect p95 | Detect max | Closed within 60 s of release | Close p50 | Close p95 |
|---|---|---|---|---|---|---|---|---|
| CPU Spike | 30 | 100.0% | 4 s | 4 s | 4 s | 100.0% | 6 s | 6 s |
| Memory Leak | 30 | 100.0% | 4 s | 4 s | 4 s | 100.0% | 6 s | 6 s |

Parameters:

- Command: `.venv/Scripts/python target_app/benchmark_detection.py`
- Python 3.11.9; false-positive runs M=20 (seeds 0..19), fault runs N=30 per fault (seeds 0..29)
- Jitter streams: 10 simulated minutes at SAMPLE_INTERVAL_SEC=2 s, idle CPU 0.5-6 %, RAM 130 +/- 1.5 MB, a 25 % CPU bump every 37th sample
- Warm-up before injection: 40 idle samples (FIRST_FIT_SAMPLES=15)
- CPU spike: 3 samples at about 95 % (MAX_SPIKE_SEC=5); memory leak: +60 MB (MAX_LEAK_STEP_MB), released as soon as it is detected
- Detection time: seconds from the last sample before injection to the incident opening. Close time: seconds from release (CPU: end of the spike) to the incident closing
- Config: CPU_MIN_DELTA=15.0, RAM_MIN_DELTA_MB=30.0, OPEN_AFTER=2, CLOSE_AFTER=3, TRAIN_WINDOW=150, REFIT_INTERVAL_SEC=300

Reading the numbers: the sample sizes are modest (20 jitter streams, 30 runs per fault), so "0 false incidents in 3.3 simulated hours" is evidence, not a guarantee. Detection time is the same 4 s in every run (the two samples needed to open, 2 s apart) because the synthetic faults are well above the thresholds and the detector is deterministic; faults near the 15-point CPU or 30 MB memory thresholds would be slower or missed.

## Safety in public demo mode

Set `PUBLIC_DEMO=1` (the Render Blueprint does) when the app is reachable by anyone:
Expand Down Expand Up @@ -147,7 +174,7 @@ ruff check . && ruff format --check .
pytest --cov=target_app
```

143 tests. They use temporary directories, disable the background threads (or drive them with a fake clock) and replace the Gemini call with stubs, so they never touch the network. They cover the detector (jitter, spikes, held leaks, baseline refresh, warm-up), incident timelines and measured times, the live pipeline through a whole incident (and a new fault right after one resolves), the incident statistics, report sources, wording per fault kind, linking and download, the guided demo end to end (with a fast fake watchdog), the status strip, snapshots (readability, contents, freshness) and rollback, corruption detection, public demo mode, fault caps, cooldowns and auto-release, the alert rules (validation, the pending, firing and resolved states with a fake clock, webhook limits), the likely-cause rules and the merged timeline, the `/metrics` output and the monitoring files, the OpenAPI tags and the main API endpoints. CI runs them on Python 3.11 and 3.12, lints with ruff, and builds and smoke-tests the Docker image.
144 tests. They use temporary directories, disable the background threads (or drive them with a fake clock) and replace the Gemini call with stubs, so they never touch the network. They cover the detector (jitter, spikes, held leaks, baseline refresh, warm-up), incident timelines and measured times, the live pipeline through a whole incident (and a new fault right after one resolves), the incident statistics, report sources, wording per fault kind, linking and download, the guided demo end to end (with a fast fake watchdog), the status strip, snapshots (readability, contents, freshness) and rollback, corruption detection, public demo mode, fault caps, cooldowns and auto-release, the alert rules (validation, the pending, firing and resolved states with a fake clock, webhook limits), the likely-cause rules and the merged timeline, the `/metrics` output and the monitoring files, the OpenAPI tags and the main API endpoints. CI runs them on Python 3.11 and 3.12, lints with ruff, and builds and smoke-tests the Docker image.

## Deploy on Render

Expand Down
2 changes: 1 addition & 1 deletion docs/sdlc.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Every user and system flow, with the functions involved, is in [process-flows.md

## 4. Testing

`pytest --collect-only -q` (run in `.venv`) collects 143 tests. The grouping below is by test file, so each level is a judgement based on the [README](../README.md) test section and the file names.
`pytest --collect-only -q` (run in `.venv`) collects 144 tests. The grouping below is by test file, so each level is a judgement based on the [README](../README.md) test section and the file names.

| Level | What it covers | Where | Count |
|---|---|---|---|
Expand Down
203 changes: 203 additions & 0 deletions target_app/benchmark_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
"""Reproducible reliability benchmark for the DeepBell anomaly detector.

Runs the real ``Detector`` with the real config constants on seeded synthetic sample streams
and a fake clock (no threads, no network, no real faults). It measures:

1. false incidents on jitter-only streams,
2. detection latency for a CPU spike and a memory leak, sized like the Chaos Lab faults,
3. how fast an open incident closes once the fault is released.

It is a simulation of the detector, not production telemetry, and "recovery" here means the
detector noticing normal samples again, not a real process recovering.

Run from the repository root: .venv/Scripts/python target_app/benchmark_detection.py
"""

import argparse
import math
import platform
import random
import sys

from deepbell import config, detection

DETECT_WITHIN_SEC = 60.0
CLOSE_WITHIN_SEC = 60.0
WARMUP_SAMPLES = 40 # past FIRST_FIT_SAMPLES, so the first fit has happened
JITTER_MINUTES = 10 # default stream length; the forest fit per bump makes longer runs slow
DEFAULT_M, DEFAULT_N = 20, 30
# Fault sizes follow the Chaos Lab: a spike lasts MAX_SPIKE_SEC at ~95 % CPU (as in the tests),
# a leak step is MAX_LEAK_STEP_MB on top of the ~130 MB idle level.
SPIKE_CPU = 95.0
SPIKE_SAMPLES = math.ceil(config.MAX_SPIKE_SEC / config.SAMPLE_INTERVAL_SEC)
LEAK_MB = float(config.MAX_LEAK_STEP_MB)
LEAK_HOLD_SAMPLES = 60 # give up waiting for detection after this many samples
FAULTS = ("cpu_spike", "memory_leak")


class Clock:
def __init__(self):
self.t = 0.0

def tick(self):
self.t += config.SAMPLE_INTERVAL_SEC
return self.t


def idle(rng):
"""One idle sample: a few % CPU and ~130 MB with normal jitter (as in tests/test_watchdog)."""
return rng.uniform(0.5, 6.0), 130.0 + rng.uniform(-1.5, 1.5)


def percentile(values, q):
"""Nearest-rank percentile; None for an empty list."""
if not values:
return None
ordered = sorted(values)
return ordered[max(0, math.ceil(q / 100 * len(ordered)) - 1)]


def false_positive_run(seed, minutes=JITTER_MINUTES):
"""Jitter-only stream with occasional single bumps. Returns (incidents opened, seconds)."""
rng, clock, det = random.Random(seed), Clock(), detection.Detector()
n = int(minutes * 60 / config.SAMPLE_INTERVAL_SEC)
samples = [idle(rng) for _ in range(n)]
for i in range(20, n, 37):
samples[i] = (25.0, samples[i][1])
opened = 0
for cpu, ram in samples:
opened += len(det.observe(cpu, ram, clock.tick())[1])
return opened, n * config.SAMPLE_INTERVAL_SEC


def fault_run(kind, seed):
"""Warm up, inject a fault, release it. Returns (detect_sec, close_sec); None if missed."""
rng, clock, det = random.Random(seed), Clock(), detection.Detector()
for _ in range(WARMUP_SAMPLES):
det.observe(*idle(rng), clock.tick())
injected_at = clock.t
if kind == "cpu_spike":
fault = [
(SPIKE_CPU + rng.uniform(-3, 3), 130.0 + rng.uniform(-1.5, 1.5))
for _ in range(SPIKE_SAMPLES)
]
else:
fault = [
(rng.uniform(0.5, 6.0), 130.0 + LEAK_MB + rng.uniform(-1, 1))
for _ in range(LEAK_HOLD_SAMPLES)
]
detect = None
for cpu, ram in fault:
_, opened, _ = det.observe(cpu, ram, clock.tick())
if opened and detect is None:
detect = clock.t - injected_at
if kind == "memory_leak":
break # the leak is released as soon as it is detected
if detect is None:
return None, None
released_at = clock.t
for _ in range(int(CLOSE_WITHIN_SEC * 4 / config.SAMPLE_INTERVAL_SEC)):
_, _, closed = det.observe(*idle(rng), clock.tick())
if closed:
return detect, clock.t - released_at
return detect, None


def run_benchmark(m=DEFAULT_M, n=DEFAULT_N, minutes=JITTER_MINUTES):
runs = [false_positive_run(seed, minutes) for seed in range(m)]
total_incidents = sum(o for o, _ in runs)
hours = sum(s for _, s in runs) / 3600
result = {
"false_positive": {
"runs": m,
"incidents": total_incidents,
"hours": hours,
"incidents_per_hour": total_incidents / hours if hours else 0.0,
"runs_with_false_incident": sum(1 for o, _ in runs if o) / m if m else 0.0,
},
"faults": {},
}
for kind in FAULTS:
results = [fault_run(kind, seed) for seed in range(n)]
det = [d for d, _ in results if d is not None]
closes = [c for d, c in results if d is not None and c is not None]
result["faults"][kind] = {
"runs": n,
"detected": len(det),
"detection_rate": sum(1 for d in det if d <= DETECT_WITHIN_SEC) / n if n else 0.0,
"detect_p50": percentile(det, 50),
"detect_p95": percentile(det, 95),
"detect_max": max(det) if det else None,
"recovery_rate": (
sum(1 for c in closes if c <= CLOSE_WITHIN_SEC) / len(det) if det else 0.0
),
"close_p50": percentile(closes, 50),
"close_p95": percentile(closes, 95),
"close_max": max(closes) if closes else None,
}
return result


def fmt(v):
return "n/a" if v is None else f"{v:.0f} s"


def render(result, m, n, command, minutes=JITTER_MINUTES):
fp = result["false_positive"]
lines = [
"| Runs | Simulated hours | False incidents | Incidents per hour | Runs with a false incident |",
"|---|---|---|---|---|",
f"| {fp['runs']} | {fp['hours']:.1f} | {fp['incidents']} | "
f"{fp['incidents_per_hour']:.3f} | {fp['runs_with_false_incident']:.1%} |",
"",
f"| Fault | Runs | Detected within {DETECT_WITHIN_SEC:.0f} s | Detect p50 | Detect p95 "
f"| Detect max | Closed within {CLOSE_WITHIN_SEC:.0f} s of release | Close p50 | Close p95 |",
"|---|---|---|---|---|---|---|---|---|",
]
for kind, f in result["faults"].items():
lines.append(
f"| {config.SAMPLE_LABELS[kind]} | {f['runs']} | {f['detection_rate']:.1%} | "
f"{fmt(f['detect_p50'])} | {fmt(f['detect_p95'])} | {fmt(f['detect_max'])} | "
f"{f['recovery_rate']:.1%} | {fmt(f['close_p50'])} | {fmt(f['close_p95'])} |"
)
lines += [
"",
"Parameters:",
"",
f"- Command: `{command}`",
f"- Python {platform.python_version()}; false-positive runs M={m} (seeds 0..{m - 1}), "
f"fault runs N={n} per fault (seeds 0..{n - 1})",
f"- Jitter streams: {minutes} simulated minutes at SAMPLE_INTERVAL_SEC="
f"{config.SAMPLE_INTERVAL_SEC} s, idle CPU 0.5-6 %, RAM 130 +/- 1.5 MB, a 25 % CPU bump "
"every 37th sample",
f"- Warm-up before injection: {WARMUP_SAMPLES} idle samples (FIRST_FIT_SAMPLES="
f"{config.FIRST_FIT_SAMPLES})",
f"- CPU spike: {SPIKE_SAMPLES} samples at about {SPIKE_CPU:.0f} % (MAX_SPIKE_SEC="
f"{config.MAX_SPIKE_SEC}); memory leak: +{LEAK_MB:.0f} MB (MAX_LEAK_STEP_MB), released as "
"soon as it is detected",
"- Detection time: seconds from the last sample before injection to the incident opening. "
"Close time: seconds from release (CPU: end of the spike) to the incident closing",
f"- Config: CPU_MIN_DELTA={config.CPU_MIN_DELTA}, "
f"RAM_MIN_DELTA_MB={config.RAM_MIN_DELTA_MB}, OPEN_AFTER={config.OPEN_AFTER}, "
f"CLOSE_AFTER={config.CLOSE_AFTER}, TRAIN_WINDOW={config.TRAIN_WINDOW}, "
f"REFIT_INTERVAL_SEC={config.REFIT_INTERVAL_SEC}",
]
return "\n".join(lines)


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("-m", type=int, default=DEFAULT_M, help="false-positive runs")
parser.add_argument("-n", type=int, default=DEFAULT_N, help="runs per fault kind")
parser.add_argument("--minutes", type=int, default=JITTER_MINUTES, help="jitter stream length")
args = parser.parse_args(argv)
command = ".venv/Scripts/python target_app/benchmark_detection.py"
if (args.m, args.n, args.minutes) != (DEFAULT_M, DEFAULT_N, JITTER_MINUTES):
command += f" -m {args.m} -n {args.n} --minutes {args.minutes}"
result = run_benchmark(args.m, args.n, args.minutes)
print(render(result, args.m, args.n, command, args.minutes))
return 0


if __name__ == "__main__":
sys.exit(main())
16 changes: 16 additions & 0 deletions tests/test_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""The reliability benchmark runs and returns sane numbers (tiny M and N)."""

import benchmark_detection as bench


def test_benchmark_runs_with_sane_fields():
result = bench.run_benchmark(m=1, n=2)
fp = result["false_positive"]
assert fp["runs"] == 1 and fp["incidents_per_hour"] >= 0
assert 0 <= fp["runs_with_false_incident"] <= 1
assert set(result["faults"]) == {"cpu_spike", "memory_leak"}
for f in result["faults"].values():
assert 0 <= f["detection_rate"] <= 1
assert 0 <= f["recovery_rate"] <= 1
assert f["detect_p50"] is None or f["detect_p50"] <= f["detect_p95"] <= f["detect_max"]
assert "| Fault |" in bench.render(result, 1, 2, "cmd")
Loading