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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# DeepBell

A mini SRE lab in FastAPI: it detects its own CPU and memory anomalies, writes incident reports, and restores from snapshots.
**Catches what breaks in a running app, finds the likely cause and writes the incident report.** A mini SRE lab in FastAPI: it detects its own CPU and memory anomalies, writes incident reports, and restores from snapshots.

Monitoring usually stops at an alert. DeepBell practises the steps after it: **detect → report → recover**. A background thread samples the service's own CPU and memory every 2 s, a baseline check plus an Isolation Forest flags anomalies and opens de-duplicated incidents, each incident gets a Markdown report (Google Gemini through LangChain when a key is set, a built-in template otherwise), and rolling SQLite snapshots give one-click rollback. A capped Chaos Lab lets you break it on purpose.

Expand All @@ -24,7 +24,7 @@ The demo is one shared instance on Render's free plan: everyone sees the same te
- **Self-monitoring watchdog.** A background thread samples the process's own CPU and resident memory every 2 s with `psutil` and scores each sample against a learned baseline (see [Detection logic](#detection-logic)).
- **Incidents and timelines.** Every incident records when it started (the injected fault, or its first anomalous sample), when it was detected and when it resolved, plus the reports and recovery actions in between. The Incidents view lists them with filters and shows each one's time to detect and time to recover, a lifecycle bar drawn to scale and its timeline. Times are computed from the server's own timestamps and labelled as demo measurements.
- **Likely cause.** Each incident detail shows one merged timeline (fault injected, first anomalous sample, alerts going pending, firing and resolved, incident opened, report written, snapshot restored, incident closed, each with its offset from the start) and a "likely cause" panel: the most probable trigger, the evidence, what was checked and not found, and a confidence level (high, medium, low or unknown) from a few explainable rules. It is labelled a heuristic: a fault of the matching kind injected within 10 s of the first anomalous sample gives high confidence, and with no recorded fault the answer is "unknown". It is also in the Markdown report. See [docs/walkthroughs/03-incident-correlation.md](docs/walkthroughs/03-incident-correlation.md).
- **Incident reports.** Each incident gets a Markdown report: a deterministic built-in template by default, or Google Gemini when `GOOGLE_API_KEY` is set (with the template as fallback). The template describes only the incident's own fault: a database report never borrows a memory leak's samples. Every report is labelled with what wrote it (Gemini, template, template fallback, or the example written at startup) and downloads as `.md` with the incident's timeline and measured times appended.
- **Incident reports.** Each incident gets a Markdown report: a deterministic built-in template by default, or Google Gemini when `GOOGLE_API_KEY` is set (with the template as fallback). Gemini is given the incident's detail, timeline and likely cause as well as the telemetry, is told to use only that data and state its confidence, and its report opens with an AI-written label and ends with the evidence it was given. The template describes only the incident's own fault: a database report never borrows a memory leak's samples. Every report is labelled with what wrote it (Gemini, template, template fallback, or the example written at startup) and downloads as `.md` with the incident's timeline and measured times appended.
- **Alert rules.** Rules in [`target_app/alert_rules.json`](target_app/alert_rules.json) (metric, `>` or `<`, threshold, for-duration, severity) are checked on every sample and move through pending, firing and resolved. The shipped rules fire on each Chaos Lab fault. The Alerts view shows each rule's state and the recent changes; `GET /api/alerts` returns the same. Set `DEEPBELL_ALERT_WEBHOOK_URL` to post firing and resolved alerts to a Slack or Discord webhook (rate-limited, sent from a background thread); without it they are only logged. See [docs/walkthroughs/02-alert-rules.md](docs/walkthroughs/02-alert-rules.md).
- **Status strip.** Uptime-style bars for the last 30 minutes, built from the metrics history: healthy, flagged samples without an incident, incident open, synthetic warm-up, no data. A bar with an incident links to it.
- **Live Telemetry.** CPU and memory over 2 or 10 minutes, the detector's baseline and streaks, and a CPU-against-memory scatter plot that shows which samples crossed an alert line and became candidates for the Isolation Forest.
Expand Down Expand Up @@ -147,7 +147,7 @@ ruff check . && ruff format --check .
pytest --cov=target_app
```

142 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.
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.

## Deploy on Render

Expand Down Expand Up @@ -224,6 +224,8 @@ DeepBell/
├── docs/
│ ├── process-flows.md # Every user and system flow, with diagrams
│ ├── roadmap.md # What was built next, and what was dropped and why
│ ├── sdlc.md # How it was planned, designed, built, tested and shipped
│ ├── uat.md # User acceptance test: tasks, pass criteria, results
│ ├── walkthroughs/ # How Prometheus/Grafana, alert rules and correlation work
│ ├── screenshots/ # README and portfolio images
│ └── major_project_proposal.md
Expand Down
99 changes: 99 additions & 0 deletions docs/sdlc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Software development lifecycle: DeepBell

DeepBell is a small SRE lab in FastAPI. It samples its own CPU and memory, flags anomalies, writes incident reports and restores SQLite snapshots ([README](../README.md)). It was built by one author, Chandana Vishnu Jayanth, in short iterations. Early work went straight to `main`. From 2026-10-23 onward, changes went through small branches merged to `main` by pull request. The first commit is dated 2026-06-04 and the latest 2026-11-07. `git rev-list --count HEAD` gives 45 commits. There are 10 merge commits (pull requests #3 to #12). Pull request #1 appears in a commit title as a squash merge.

## 1. Planning and requirements

The original requirements are in [major_project_proposal.md](major_project_proposal.md). It states the problem: static-threshold monitoring only alerts, so recovery time is long and root causes need manual log reading. The target users are SRE-minded engineers and the project's examiners. The proposal fixes four modules:

- A FastAPI and SQLite target app with fault injection (CPU spike, memory leak, fatal exception).
- A rolling point-in-time snapshot engine.
- An ML watchdog using psutil and an Isolation Forest.
- A LangChain responder that rolls back and writes a root cause report with an LLM.

Its deliverables are a working monitoring agent, an automated recovery demonstration, generated reports and a GitHub repository. It names no numeric non-functional targets.

The delivered project differs from the proposal in these ways:

- It adds a public demo with caps and cooldowns ([README](../README.md), "Live demo").
- It adds a template report used when no Gemini key is set.
- It adds a Prometheus endpoint, alert rules and incident correlation, which the [roadmap](roadmap.md) records.
- It leaves out three things the proposal lists: log parsing, I/O telemetry and pandas. No Python file in the repo parses logs or samples disk I/O, and `pandas` is not in [requirements.txt](../target_app/requirements.txt).

Out of scope, per the [roadmap](roadmap.md): OpenTelemetry tracing (dropped), monitoring other Render demos (deferred), and anything that needs a paid service, a database server or a second always-on process.

## 2. Design

The backend is one FastAPI process with one uvicorn worker. The watchdog thread, snapshot thread, open incidents and Chaos Lab state all live in that process ([Dockerfile](../Dockerfile) comments). The code is split into a `deepbell` package with one module per job: detection, incidents, snapshots, chaos, demo, alert rules, correlation, and a `routes/` folder. See [target_app/deepbell](../target_app/deepbell/). The UI is a Jinja2 template with static JavaScript.

Storage is SQLite. Incident history lives in `metrics.db`, separate from `app.db`, so corrupting or rolling back the application database does not rewrite it ([README](../README.md)). Snapshots are copies of `app.db`, taken every 30 s when the contents change. The newest 10 are kept, each integrity-checked.

Design decisions the docs record:

- The roadmap explains why tracing was dropped and why other demos are not monitored (free-plan limits).
- Alert rules live in a versioned file, [alert_rules.json](../target_app/alert_rules.json).
- Likely cause is a labelled heuristic, not a claim of certainty.

Every user and system flow, with the functions involved, is in [process-flows.md](process-flows.md). Feature walkthroughs are in [docs/walkthroughs](walkthroughs/).

## 3. Implementation

- **Stack:** Python 3.11 and 3.12. Runtime pins in [requirements.txt](../target_app/requirements.txt): fastapi 0.104.1, uvicorn 0.24.0.post1, jinja2 3.1.2, psutil 5.9.6, numpy 1.26.4, scikit-learn 1.3.2, langchain-core 0.1.16, langchain-google-genai 0.0.6, prometheus-client 0.26.0.
- **Dev tools:** [requirements-dev.txt](../requirements-dev.txt) pins pytest 9.1.1, pytest-cov 7.1.0, httpx 0.27.2, ruff 0.6.9 and pyyaml 6.0.3.
- **Layout:** `target_app/` holds the app, `tests/` the tests, `monitoring/` the Prometheus and Grafana stack, `docs/` the documents. `run_all.py` is the local entry point. `reports/` holds generated sample incident reports.
- **Standards:** ruff checks and formats, configured in [pyproject.toml](../pyproject.toml) (line length 100, rules E, F, W, I, B, UP). CI enforces both.
- **Workflow:** the history has 18 commits before pull request #1, made directly on `main`. The module split of a 2,700-line `main.py` was done on 2026-11-01. Merged branch names from the merge messages: add-mit-license, readme-license, readme-case-study, fix/functionality, feat/prometheus-grafana, feat/alert-rules, feat/incident-correlation, test-temp-cleanup, proofread, upgrade-pytest. Some commits after #1 and before #3 (2026-10-31, 2026-11-01) were also made directly on `main`.

## 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.

| Level | What it covers | Where | Count |
|---|---|---|---|
| Unit | Watchdog, detector, snapshots, rollback | [test_watchdog.py](../tests/test_watchdog.py) | 15 |
| Unit | Alert rules, states, webhook limits (fake clock) | [test_alerts.py](../tests/test_alerts.py) | 28 |
| Unit | Likely-cause rules and merged timeline | [test_correlation.py](../tests/test_correlation.py) | 15 |
| API | Endpoints, report wording, guided demo run end to end | [test_app.py](../tests/test_app.py) | 37 |
| API and end-to-end | Console features, pipeline through an incident | [test_features.py](../tests/test_features.py), [test_console.py](../tests/test_console.py) | 20 + 19 |
| API | `/metrics` output | [test_metrics.py](../tests/test_metrics.py) | 5 |
| Monitoring config | Prometheus and Grafana files | [test_monitoring_files.py](../tests/test_monitoring_files.py) | 4 |
| CI only | Container smoke test in public demo mode | [ci.yml](../.github/workflows/ci.yml) | 4 curl checks |
| CI only | `ruff check` and `ruff format --check` | [ci.yml](../.github/workflows/ci.yml) | not counted |

Tests use temporary directories, stub Gemini and disable or fake the background threads ([README](../README.md)). Faults are injected in the end-to-end tests, which the [roadmap](roadmap.md) says each new feature adds. The counts above are per file, so those tests are not counted separately. CI runs the suite on Python 3.11 and 3.12 with `pytest --cov=target_app --cov-report=term-missing`. It reports coverage but sets no minimum.

Not tested: there is no user acceptance testing and no browser-driven test (no Selenium, Playwright or Cypress in the dev requirements or the CI workflow). The front-end JavaScript has no automated tests.

## 5. Deployment

The [Dockerfile](../Dockerfile) builds from `python:3.11-slim`, installs the pinned requirements, runs as an unprivileged user and starts one uvicorn worker on `$PORT`. [render.yaml](../render.yaml) deploys it to Render's free plan in Singapore, with `healthCheckPath: /healthz`, `autoDeployTrigger: checksPass` and `PUBLIC_DEMO=1`. The disk is ephemeral and the app seeds itself on startup. The live demo is stated as [deepbell.onrender.com](https://deepbell.onrender.com).

There is one environment: production. No staging or UAT environment is defined.

```mermaid
flowchart LR
A[Feature branch] --> B[Pull request to main]
B --> C[CI: ruff, pytest 3.11 and 3.12, Docker smoke test]
C --> D[Merge to main]
D --> E[Render redeploys when checks pass]
E --> F[Health check /healthz]
```

## 6. Operations and maintenance

- **Monitoring:** the app exposes `/metrics`. [prometheus.yml](../monitoring/prometheus.yml) scrapes it every 5 s. [docker-compose.yml](../monitoring/docker-compose.yml) starts Prometheus and Grafana with a provisioned dashboard, [deepbell.json](../monitoring/grafana/dashboards/deepbell.json). This stack is for local use. The README does not say it runs for the live demo.
- **Alerting:** in-app rules from `alert_rules.json`, with a pending, firing and resolved lifecycle, an Alerts view and optional webhooks ([walkthrough](walkthroughs/02-alert-rules.md)).
- **Health checks:** `/healthz`, used by Render and by CI.
- **Dependencies:** all pinned exactly. The last recorded update is pytest 9.1.1 and pytest-cov 7.1.0 (2026-11-07). No automated update tool is configured in the repo.
- **Roadmap:** [roadmap.md](roadmap.md) lists three features, all now merged, and what is not planned.

## 7. Gaps and next steps

- **No UAT.** Nobody outside the author is recorded as having tested it. Next step: run the task list in [uat.md](uat.md) with three to five people and record the results there.
- **No browser-driven tests.** Front-end code is untested. Next step: add a Playwright smoke test of the guided demo.
- **No staging environment.** Merges to `main` deploy straight to the demo. Next step: add a second Render service from a branch.
- **Single author, so no peer review.** Pull requests are self-merged. Next step: ask a reviewer to approve changes, or enable branch protection.
- **Some work went directly to `main`.** Next step: require pull requests on `main`.
- **No coverage threshold.** Next step: set `--cov-fail-under` in CI.
- **Old runtime pins.** FastAPI 0.104.1 and langchain-core 0.1.16 are old. Next step: add Dependabot and upgrade deliberately.
- **Monitoring stack is local only.** Next step: say so in the README, or host it.
60 changes: 60 additions & 0 deletions docs/uat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# User acceptance test: DeepBell

## Who to test with

Test with 3 to 5 people who have never seen DeepBell. Mix them:

- 2 students or junior developers (your likely recruiters' peers).
- 1 person who has heard of monitoring or on-call work.
- 1 non-technical person, if you can.

Do not explain the app first. Do not help during a task. Note where they hesitate.

## Setup

- Live demo: open https://deepbell.onrender.com (from the README). If the site slept, note the wait time as part of Task 1. The README says the first visit can take about a minute.
- Local alternative: from the repo root run `python run_all.py` (named in the README) and open the address it prints.
- Use one laptop browser. Run one tester on a phone as well.
- Use a stopwatch. Ask testers to think aloud. Only one tester at a time on the live demo, because it is a shared server with cooldowns.
- Tell the tester only: "This is a website. Try to do the tasks. I will not help."

## Tasks

Read each task aloud. Stop a task at 3 minutes and mark it a fail.

**T1. Get started.** "Open the site and tell me, in your own words, what it is for."
Pass: the tester says it watches a server and writes reports when something goes wrong, within 60 seconds of the page showing. Time any wait for the page to load.

**T2. See it work.** "Show me the system detecting a problem by itself."
Pass: the tester starts the guided demo and sees at least the first incident open, without help.

**T3. Read the result.** "Find out what went wrong in the incident and how long it took to notice it."
Pass: the tester opens an incident or report and states the fault and the time to detect, correctly.

**T4. Judge the report.** "Tell me whether the report was written by a person, a template or an AI, and how sure it is of the cause."
Pass: the tester gives the right source (as shown on the report) and finds the confidence level or says there is none.

**T5. Break something yourself.** "Cause a problem of your own choosing, then put the system back to normal."
Pass: the tester injects a fault and restores normal state (release memory or roll back), and reads any limit or cooldown message correctly without help.

## Post-test questions

1. What was the most confusing moment, and where were you when it happened?
2. Would you trust the cause in the report enough to act on it? Why or why not?
3. What would you tell a friend this app does, in one sentence?

## Results

| Tester | T1 | T2 | T3 | T4 | T5 | Time (total) | Notes |
|---|---|---|---|---|---|---|---|
| 1 | | | | | | | |
| 2 | | | | | | | |
| 3 | | | | | | | |
| 4 | | | | | | | |
| 5 | | | | | | | |

Mark each task pass or fail.

## Sign-off

Tested by: ____________________ Date: ____________ Build or commit: ____________ Result (pass if at least 4 of 5 testers pass T1 to T3): ____________
Loading
Loading