Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(detections): backtest a rule over historical lake events (W2.1) (#574)
Beenu Arora2bfa811553f8
diff --git a/AGENTS.md b/AGENTS.mdindex 22d557770..1282ed7f1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,7 +10,8 @@- Benchmark data and documentation must be transparent about what is synthetic vs. real; never present fabricated metrics as actual measured performance.- When the task is clear, act autonomously — don't ask unnecessary clarifying questions.- Standing repo-maintenance loop is the default when no other task is queued: review open PRs at the canonical repo, resolve CI/conflicts, merge them, close issues those PRs resolved, and keep `main` green.-- After any deploy to `tryaisoc.com`, do an end-to-end customer-journey review (landing → dashboard) and fix broken links or interactive failures before declaring the task done — the user has repeatedly flagged broken items post-deploy.+- After any deploy to `tryaisoc.com`, do an end-to-end customer-journey review that covers the full **authenticated** app (registration → login → connector setup → live ingest/triage → billing), not just landing → dashboard: click through every interactive element and fix dead buttons, broken flows, and empty/errored views before declaring done. The user repeatedly reports broken authenticated features post-deploy and demands being "1000% sure" nothing is broken before any handover.+- The authenticated product must run on **real, live** connector-ingested data and genuine LLM triage — never mock/demo/baseline-fallback or empty data presented as working. When a user connects a connector, the platform must automatically and continuously (near-real-time) pull and analyze that data for triage without the user having to ask; stubbed features, empty dashboards, and silent mock-data fallbacks are treated as bugs.- When asked "what else can we improve?" / "what are the missing pieces?" / "make this world-class", produce a concrete competitive gap analysis vs. leading commercial AI-SOC products and implement the gaps — don't just answer in prose.## Learned Workspace Facts@@ -82,3 +83,4 @@- **Detection corpus honesty.** `detections/` carries ~6,975 rules on disk, but only ~939 are **executable** today (861 native + 77 Sigma-imported + 1 community); the remainder are quarantined/disabled. A truth-table documents the executable-vs-quarantined split. Keep these counts honest — never present quarantined/aspirational rules as executable (same synthetic-vs-real transparency rule as the eval harness).- **Stateful stores + per-store tenant isolation.** Beyond Postgres/Redis the platform runs Kafka (Redpanda-compatible in CI: KRaft, no ZooKeeper), ClickHouse (event lake, table `aisoc.raw_events`), Neo4j (entity graph), and Qdrant (vector store in `services/threatintel` via `QdrantStore`, for IOC/actor embeddings). This complements the query-layer Postgres isolation on `/hunts` + `/cases`: ClickHouse scopes via `lake_sql.rewrite_for_tenant()` injecting a `tenant_id` predicate into user SQL; Neo4j via a `tenant_id` node-property filter; Redis via a `tenant:{tid}:` key-prefix; Kafka via the `X-Tenant-ID` header / `tenant_id` envelope with per-tenant downstream filtering; Qdrant via `tenant_id` in point payloads + a mandatory query filter (public feed intel is intentionally global, so scoping targets tenant-private data). Offline assertions live in `tests/isolation/`; a CI live-container replay seeds two tenants and asserts cross-tenant reads never leak (skips gracefully when containers are absent).- **Production event-flow spine + response posture.** The CI-gated production path is: Connectors → `services/ingest` (OCSF normalize) → Kafka `raw_events` → `services/fusion` (promote + fuse) → Postgres alerts + `services/realtime` WS; the fusion consumer validates event schema and routes poison events to a dead-letter queue (they were previously dropped silently). Default response/autonomy posture is **copilot / dry-run** (human approval required); SOAR executors return `simulated` results unless real vendor credentials are plumbed. Populating the ClickHouse lake and running the detection corpus against the live stream are tracked roadmap items (a lake-writer / detect worker), so live-stream detection may not be wired in a given checkout — verify before assuming it runs.+- **Standing repo-maintenance loop — Dependabot + CodeQL gotchas.** The canonical repo carries frequent Dependabot PRs touching both `poetry.lock` (Python services) and `pnpm-lock.yaml` (JS workspaces); merging lockfile PRs one-by-one re-conflicts the siblings, so consolidate them into a few **re-locked batch PRs** (regenerate the locks locally, verify exact target versions, merge once) instead of dozens of serial rebases. CodeQL requires `codeql-action` `init` / `autobuild` / `analyze` to all run on the **same** version — when Dependabot splits a `codeql-action` bump across separate PRs the CodeQL gate fails, so combine all legs of that bump into one PR.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 06c1914ce..dc0072257 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Detection backtesting over the event lake (Wave 2).** New+ `POST /api/v1/rules/{rule_id}/backtest` runs a candidate detection rule against+ REAL historical events in the tenant-scoped ClickHouse lake+ (`aisoc.raw_events`) over a bounded window and reports exactly how many events+ would have fired (`would_fire`), the `hit_rate`, and sample matches — so an+ engineer can see a rule's noise on real history before promoting it, instead of+ only testing against hand-crafted fixtures. The source filter is+ injection-sanitised and the SELECT is tenant-rewritten via+ `lake_sql.rewrite_for_tenant`. Read-only (`rules:read`). Gate: `test_backtest.py`.- **Closed loop: outcomes compound, repeat alerts auto-suppress (Wave 1).** Everydurable auto-triage outcome is now written back as a per-signature institutionalprior (`services/agents/app/memory/outcomes.py`), and a later alert matching adiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex d0e884044..61ffc1015 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -52,11 +52,12 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Institutional memory nudges fuse-time confidence (bounded, per-tenant) | README (compounding memory) | `ci.yml` fusion job (`test_memory_nudge.py` — distilled per-signature priors nudge new alerts of that signature ±0.10 in `ConfidenceScorer`; unknown signatures unchanged; `MemoryPriorProvider` distils per-tenant priors from disposition history so one tenant never nudges another) | GATED | - || Scheduled hunt findings flow into governed detection proposals | README (proactive hunting → detections) | `ci.yml` api job (`test_wave1_loop_edges.py` — a scheduled hunt that returns hits opens a DRAFT `DetectionRuleProposal` (source `hunt-finding`) into the propose→review→eval-gate→promote lifecycle; zero-hit / flag-off paths open nothing) | GATED | - || Analyst disposition history drives human-approval-gated tuning proposals | README (self-improving detections) | `ci.yml` api job (`test_wave1_loop_edges.py` — the previously-orphaned `suggest_tuning` engine is wired to real per-rule disposition history via `/detection/tuning/auto-suggest`, opening DRAFT proposals; `test_detection_tuner.py` fixture-gates the engine) | PARTIAL (mapping + wiring gated; end-to-end proposal insert exercised in api integration, not a unit DB) | Phase 2 |+| Detections can be backtested over historical lake data before promotion | README (detection engineering) | `ci.yml` api job (`test_backtest.py` — bounded/allow-listed SQL construction with injection-sanitised source filter, lake-row→event mapping with JSON payload expansion, exact would-fire count + hit-rate + samples) | PARTIAL (pure backtest logic gated; the live tenant-scoped ClickHouse fetch is exercised by the integration gate, not a unit) | Phase 2 |## Summary- GATED: 36-- PARTIAL: 8+- PARTIAL: 9- NO GATE: 0 (**every claim is now 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 full Fully-Operational roadmap (Phases A1–E1) is complete. The 7 remaining PARTIAL rows are honest, named deferrals to future phases outside the A–E scope — each states the specific gap and the phase that closes it — not unproven claims.)The ratchet is enforced by `scripts/check_claim_gate_matrix.py` (wired into `security.yml`): the NO GATE count may only decrease.diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 8fa632630..13fd2782a 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -2683,6 +2683,47 @@ paths:$ref: '#/components/schemas/HTTPValidationError'security:- HTTPBearer: []+ /api/v1/rules/{rule_id}/backtest:+ post:+ tags:+ - detection_rules+ summary: Backtest a detection rule against historical lake events+ description: 'Run a rule over the last N days of REAL events in the ClickHouse+ lake and++ report exactly how many would have fired (Wave 2). Tenant-scoped via++ ``lake_sql.rewrite_for_tenant``. Read-only.'+ operationId: backtest_detection_rule_api_v1_rules__rule_id__backtest_post+ security:+ - HTTPBearer: []+ parameters:+ - name: rule_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Rule Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BacktestRequest'+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BacktestResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/detection/rules:get:tags:@@ -15094,6 +15135,73 @@ components:- tenant_id- actionstitle: AutonomyPolicyResponse+ BacktestRequest:+ properties:+ window_days:+ type: integer+ maximum: 365.0+ minimum: 1.0+ title: Window Days+ description: How many days of history to scan.+ default: 30+ limit:+ type: integer+ maximum: 100000.0+ minimum: 1.0+ title: Limit+ description: Max events to scan.+ default: 5000+ source:+ anyOf:+ - type: string+ - type: 'null'+ title: Source+ description: Optional connector_type filter (e.g. 'okta_system_log').+ type: object+ title: BacktestRequest+ description: Backtest a rule over historical lake events.+ BacktestResponse:+ properties:+ rule_id:+ type: string+ format: uuid+ title: Rule Id+ rule_language:+ type: string+ title: Rule Language+ window_days:+ type: integer+ title: Window Days+ events_scanned:+ type: integer+ title: Events Scanned+ would_fire:+ type: integer+ title: Would Fire+ hit_rate:+ type: number+ title: Hit Rate+ sample_matches:+ items:+ additionalProperties: true+ type: object+ type: array+ title: Sample Matches+ error:+ anyOf:+ - type: string+ - type: 'null'+ title: Error+ type: object+ required:+ - rule_id+ - rule_language+ - window_days+ - events_scanned+ - would_fire+ - hit_rate+ - sample_matches+ title: BacktestResponseBaselineResponse:properties:id:diff --git a/infra/terraform/environments/aws/scale.plan b/infra/terraform/environments/aws/scale.plannew file mode 100644index 000000000..6dac03f44Binary files /dev/null and b/infra/terraform/environments/aws/scale.plan differdiff --git a/infra/terraform/environments/aws/tf.plan b/infra/terraform/environments/aws/tf.plannew file mode 100644index 000000000..b4f45f6daBinary files /dev/null and b/infra/terraform/environments/aws/tf.plan differdiff --git a/infra/terraform/environments/aws/tf2.plan b/infra/terraform/environments/aws/tf2.plannew file mode 100644index 000000000..2daad86fcBinary files /dev/null and b/infra/terraform/environments/aws/tf2.plan differdiff --git a/screenshots/01-landing.png b/screenshots/01-landing.pngnew file mode 100644index 000000000..f7b0a1c89Binary files /dev/null and b/screenshots/01-landing.png differdiff --git a/screenshots/02-signup.png b/screenshots/02-signup.pngnew file mode 100644index 000000000..998749909Binary files /dev/null and b/screenshots/02-signup.png differdiff --git a/screenshots/redesign/about-full.png b/screenshots/redesign/about-full.pngnew file mode 100644index 000000000..35e2dcf1eBinary files /dev/null and b/screenshots/redesign/about-full.png differdiff --git a/screenshots/redesign/app-billing.png b/screenshots/redesign/app-billing.pngnew file mode 100644index 000000000..472410bd1Binary files /dev/null and b/screenshots/redesign/app-billing.png differdiff --git a/screenshots/redesign/app-case-detail.png b/screenshots/redesign/app-case-detail.pngnew file mode 100644index 000000000..651fbb23eBinary files /dev/null and b/screenshots/redesign/app-case-detail.png differdiff --git a/screenshots/redesign/app-case-investigation.png b/screenshots/redesign/app-case-investigation.pngnew file mode 100644index 000000000..5cf4e02e2Binary files /dev/null and b/screenshots/redesign/app-case-investigation.png differdiff --git a/screenshots/redesign/app-case-ledger.png b/screenshots/redesign/app-case-ledger.pngnew file mode 100644index 000000000..382284740Binary files /dev/null and b/screenshots/redesign/app-case-ledger.png differdiff --git a/screenshots/redesign/app-cases.png b/screenshots/redesign/app-cases.pngnew file mode 100644index 000000000..1583cd724Binary files /dev/null and b/screenshots/redesign/app-cases.png differdiff --git a/screenshots/redesign/app-dashboard.png b/screenshots/redesign/app-dashboard.pngnew file mode 100644index 000000000..e45c135eeBinary files /dev/null and b/screenshots/redesign/app-dashboard.png differdiff --git a/screenshots/redesign/hero.png b/screenshots/redesign/hero.pngnew file mode 100644index 000000000..50fa3ecf5Binary files /dev/null and b/screenshots/redesign/hero.png differdiff --git a/screenshots/redesign/home-desktop.png b/screenshots/redesign/home-desktop.pngnew file mode 100644index 000000000..8cbb2733cBinary files /dev/null and b/screenshots/redesign/home-desktop.png differdiff --git a/screenshots/redesign/home-full.png b/screenshots/redesign/home-full.pngnew file mode 100644index 000000000..8cbb2733cBinary files /dev/null and b/screenshots/redesign/home-full.png differdiff --git a/screenshots/redesign/home-mobile.png b/screenshots/redesign/home-mobile.pngnew file mode 100644index 000000000..41c805466Binary files /dev/null and b/screenshots/redesign/home-mobile.png differdiff --git a/screenshots/redesign/home-tablet.png b/screenshots/redesign/home-tablet.pngnew file mode 100644index 000000000..abbb5705dBinary files /dev/null and b/screenshots/redesign/home-tablet.png differdiff --git a/screenshots/redesign/integrations-fold.png b/screenshots/redesign/integrations-fold.pngnew file mode 100644index 000000000..697f2e8f5Binary files /dev/null and b/screenshots/redesign/integrations-fold.png differdiff --git a/screenshots/redesign/integrations.png b/screenshots/redesign/integrations.pngnew file mode 100644index 000000000..491704f38Binary files /dev/null and b/screenshots/redesign/integrations.png differdiff --git a/screenshots/redesign/login.png b/screenshots/redesign/login.pngnew file mode 100644index 000000000..657f63162Binary files /dev/null and b/screenshots/redesign/login.png differdiff --git a/screenshots/redesign/pricing-full.png b/screenshots/redesign/pricing-full.pngnew file mode 100644index 000000000..3032c41f6Binary files /dev/null and b/screenshots/redesign/pricing-full.png differdiff --git a/screenshots/redesign/stripe-checkout.png b/screenshots/redesign/stripe-checkout.pngnew file mode 100644index 000000000..391ed30ffBinary files /dev/null and b/screenshots/redesign/stripe-checkout.png differdiff --git a/screenshots/redesign/tryaisoc-dashboard.png b/screenshots/redesign/tryaisoc-dashboard.pngnew file mode 100644index 000000000..8f6c000f2Binary files /dev/null and b/screenshots/redesign/tryaisoc-dashboard.png differdiff --git a/screenshots/redesign/tryaisoc-live.png b/screenshots/redesign/tryaisoc-live.pngnew file mode 100644index 000000000..5284bc2f1Binary files /dev/null and b/screenshots/redesign/tryaisoc-live.png differdiff --git a/screenshots/resweep/audit-final.png b/screenshots/resweep/audit-final.pngnew file mode 100644index 000000000..8f898929dBinary files /dev/null and b/screenshots/resweep/audit-final.png differdiff --git a/screenshots/resweep/audit.png b/screenshots/resweep/audit.pngnew file mode 100644index 000000000..cd7723f56Binary files /dev/null and b/screenshots/resweep/audit.png differdiff --git a/screenshots/resweep/coverage-advisor.png b/screenshots/resweep/coverage-advisor.pngnew file mode 100644index 000000000..44231df59Binary files /dev/null and b/screenshots/resweep/coverage-advisor.png differdiff --git a/screenshots/resweep/detection.png b/screenshots/resweep/detection.pngnew file mode 100644index 000000000..949e5d03fBinary files /dev/null and b/screenshots/resweep/detection.png differdiff --git a/screenshots/resweep/easm.png b/screenshots/resweep/easm.pngnew file mode 100644index 000000000..1815dcae4Binary files /dev/null and b/screenshots/resweep/easm.png differdiff --git a/screenshots/resweep/graph.png b/screenshots/resweep/graph.pngnew file mode 100644index 000000000..c20571e74Binary files /dev/null and b/screenshots/resweep/graph.png differdiff --git a/screenshots/resweep/shifts.png b/screenshots/resweep/shifts.pngnew file mode 100644index 000000000..45f26191eBinary files /dev/null and b/screenshots/resweep/shifts.png differdiff --git a/screenshots/resweep/threat-intel.png b/screenshots/resweep/threat-intel.pngnew file mode 100644index 000000000..b68efc482Binary files /dev/null and b/screenshots/resweep/threat-intel.png differdiff --git a/screenshots/sweep/alerts.png b/screenshots/sweep/alerts.pngnew file mode 100644index 000000000..0bc4fe012Binary files /dev/null and b/screenshots/sweep/alerts.png differdiff --git a/screenshots/sweep/audit.png b/screenshots/sweep/audit.pngnew file mode 100644index 000000000..61ba8f256Binary files /dev/null and b/screenshots/sweep/audit.png differdiff --git a/screenshots/sweep/cases.png b/screenshots/sweep/cases.pngnew file mode 100644index 000000000..87f6d3ebaBinary files /dev/null and b/screenshots/sweep/cases.png differdiff --git a/screenshots/sweep/connectors.png b/screenshots/sweep/connectors.pngnew file mode 100644index 000000000..98e4831a3Binary files /dev/null and b/screenshots/sweep/connectors.png differdiff --git a/screenshots/sweep/copilot.png b/screenshots/sweep/copilot.pngnew file mode 100644index 000000000..8ad4e11c6Binary files /dev/null and b/screenshots/sweep/copilot.png differdiff --git a/screenshots/sweep/costs.png b/screenshots/sweep/costs.pngnew file mode 100644index 000000000..88b8fb142Binary files /dev/null and b/screenshots/sweep/costs.png differdiff --git a/screenshots/sweep/coverage-advisor.png b/screenshots/sweep/coverage-advisor.pngnew file mode 100644index 000000000..34e33789aBinary files /dev/null and b/screenshots/sweep/coverage-advisor.png differdiff --git a/screenshots/sweep/dashboard.png b/screenshots/sweep/dashboard.pngnew file mode 100644index 000000000..e530af0f5Binary files /dev/null and b/screenshots/sweep/dashboard.png differdiff --git a/screenshots/sweep/dashboards-soc-insights.png b/screenshots/sweep/dashboards-soc-insights.pngnew file mode 100644index 000000000..4414eefebBinary files /dev/null and b/screenshots/sweep/dashboards-soc-insights.png differdiff --git a/screenshots/sweep/detection-catalog.png b/screenshots/sweep/detection-catalog.pngnew file mode 100644index 000000000..aaf61e34aBinary files /dev/null and b/screenshots/sweep/detection-catalog.png differdiff --git a/screenshots/sweep/detection-coverage.png b/screenshots/sweep/detection-coverage.pngnew file mode 100644index 000000000..1eb3c9323Binary files /dev/null and b/screenshots/sweep/detection-coverage.png differdiff --git a/screenshots/sweep/detection-tuning.png b/screenshots/sweep/detection-tuning.pngnew file mode 100644index 000000000..e83cc7ed5Binary files /dev/null and b/screenshots/sweep/detection-tuning.png differdiff --git a/screenshots/sweep/detection.png b/screenshots/sweep/detection.pngnew file mode 100644index 000000000..afde68b70Binary files /dev/null and b/screenshots/sweep/detection.png differdiff --git a/screenshots/sweep/easm.png b/screenshots/sweep/easm.pngnew file mode 100644index 000000000..a92ecfe6dBinary files /dev/null and b/screenshots/sweep/easm.png differdiff --git a/screenshots/sweep/explore.png b/screenshots/sweep/explore.pngnew file mode 100644index 000000000..9627fdfe7Binary files /dev/null and b/screenshots/sweep/explore.png differdiff --git a/screenshots/sweep/graph.png b/screenshots/sweep/graph.pngnew file mode 100644index 000000000..850d974dbBinary files /dev/null and b/screenshots/sweep/graph.png differdiff --git a/screenshots/sweep/hunt.png b/screenshots/sweep/hunt.pngnew file mode 100644index 000000000..57d79fac1Binary files /dev/null and b/screenshots/sweep/hunt.png differdiff --git a/screenshots/sweep/marketplace.png b/screenshots/sweep/marketplace.pngnew file mode 100644index 000000000..895454adcBinary files /dev/null and b/screenshots/sweep/marketplace.png differdiff --git a/screenshots/sweep/playbooks.png b/screenshots/sweep/playbooks.pngnew file mode 100644index 000000000..b410e9712Binary files /dev/null and b/screenshots/sweep/playbooks.png differdiff --git a/screenshots/sweep/queue.png b/screenshots/sweep/queue.pngnew file mode 100644index 000000000..7170d6550Binary files /dev/null and b/screenshots/sweep/queue.png differdiff --git a/screenshots/sweep/settings.png b/screenshots/sweep/settings.pngnew file mode 100644index 000000000..a9dab27c6Binary files /dev/null and b/screenshots/sweep/settings.png differdiff --git a/screenshots/sweep/shifts.png b/screenshots/sweep/shifts.pngnew file mode 100644index 000000000..1436f087fBinary files /dev/null and b/screenshots/sweep/shifts.png differdiff --git a/screenshots/sweep/threat-intel.png b/screenshots/sweep/threat-intel.pngnew file mode 100644index 000000000..09859a09bBinary files /dev/null and b/screenshots/sweep/threat-intel.png differdiff --git a/services/api/app/api/v1/endpoints/detection_rules.py b/services/api/app/api/v1/endpoints/detection_rules.pyindex 552bdfc9f..1e17eab98 100644--- a/services/api/app/api/v1/endpoints/detection_rules.py+++ b/services/api/app/api/v1/endpoints/detection_rules.py@@ -10,12 +10,43 @@ from sqlalchemy import and_, or_, select, updatefrom app.api.v1.deps import AuthUser, DBSession, require_permissionfrom app.models.detection_rule import DetectionRule+from app.services.backtest import backtest_rule, build_backtest_sql, rows_to_eventsfrom app.services.mssp_rule_resolver import resolve_effective_rulesfrom app.services.rule_engine import execute_rule, run_huntrouter = APIRouter(prefix="/rules", tags=["detection_rules"])+class BacktestRequest(BaseModel):+ """Backtest a rule over historical lake events."""++ window_days: int = Field(30, ge=1, le=365, description="How many days of history to scan.")+ limit: int = Field(5000, ge=1, le=100_000, description="Max events to scan.")+ source: str | None = Field(None, description="Optional connector_type filter (e.g. 'okta_system_log').")+++class BacktestResponse(BaseModel):+ rule_id: uuid.UUID+ rule_language: str+ window_days: int+ events_scanned: int+ would_fire: int+ hit_rate: float+ sample_matches: list[dict[str, Any]]+ error: str | None = None+++async def _fetch_lake_events(tenant_id: uuid.UUID, *, window_days: int, limit: int, source: str | None) -> list[dict[str, Any]]:+ """Fetch tenant-scoped historical events from the ClickHouse lake."""+ from app.db.clickhouse import execute_lake_query # noqa: PLC0415 — optional lake backend+ from app.services.lake_sql import rewrite_for_tenant # noqa: PLC0415++ sql = build_backtest_sql(window_days=window_days, limit=limit, source=source)+ rewrite = rewrite_for_tenant(sql, tenant_id, row_cap=limit)+ result = await execute_lake_query(rewrite.sql, timeout_seconds=30)+ return rows_to_events(result.columns, result.rows)++class DetectionRuleResponse(BaseModel):id: uuid.UUIDtenant_id: uuid.UUID | None@@ -398,3 +429,53 @@ async def hunt(execution_time_ms=hunt_result.execution_time_ms,errors=hunt_result.errors,)+++ "/{rule_id}/backtest",+ response_model=BacktestResponse,+ summary="Backtest a detection rule against historical lake events",+)+async def backtest_detection_rule(+ rule_id: uuid.UUID,+ request: BacktestRequest,+ current_user: Annotated[AuthUser, Depends(require_permission("rules:read"))],+ db: DBSession,+) -> BacktestResponse:+ """Run a rule over the last N days of REAL events in the ClickHouse lake and+ report exactly how many would have fired (Wave 2). Tenant-scoped via+ ``lake_sql.rewrite_for_tenant``. Read-only."""+ from app.db.clickhouse import LakeQueryNotConfiguredError # noqa: PLC0415++ rule = (+ await db.execute(+ select(DetectionRule).where(+ and_(+ DetectionRule.id == rule_id,+ or_(DetectionRule.tenant_id == current_user.tenant_id, DetectionRule.tenant_id.is_(None)),+ )+ )+ )+ ).scalar_one_or_none()+ if rule is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Detection rule not found")++ try:+ events = await _fetch_lake_events(+ current_user.tenant_id,+ window_days=request.window_days,+ limit=request.limit,+ source=request.source,+ )+ except LakeQueryNotConfiguredError as exc:+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="lake backend not configured") from exc+ except Exception as exc: # noqa: BLE001 — surface a lake failure as 502, not 500+ raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"lake query failed: {exc}") from exc++ summary = backtest_rule(rule_language=rule.rule_language, rule_body=rule.rule_body, events=events)+ return BacktestResponse(+ rule_id=rule_id,+ rule_language=rule.rule_language,+ window_days=request.window_days,+ **summary,+ )diff --git a/services/api/app/services/backtest.py b/services/api/app/services/backtest.pynew file mode 100644index 000000000..31f360b5f--- /dev/null+++ b/services/api/app/services/backtest.py@@ -0,0 +1,86 @@+"""Detection backtesting over the ClickHouse event lake (Wave 2).++Runs a candidate detection rule against REAL historical events from+``aisoc.raw_events`` (tenant-scoped) so an engineer can see exactly what a rule+would have fired on over the last N days before promoting it — the gap the+audit flagged (rules could only be tested against hand-crafted fixtures).++Honesty: the lake has no ground-truth benign/malicious labels, so this reports+``would_fire`` counts + a ``hit_rate`` (fraction of scanned events that fire),+NOT a fabricated "false-positive rate". A high hit_rate over routine history is+the noise signal an author cares about.+"""++from __future__ import annotations++import json+import re+from typing import Any++from app.services.rule_engine import evaluate_rule_over_events++# Connector types are slugs; sanitise before interpolating into lake SQL.+_SOURCE_RE = re.compile(r"[^a-z0-9_.-]")+++def sanitize_source(source: str | None) -> str | None:+ if not source:+ return None+ cleaned = _SOURCE_RE.sub("", source.lower())+ return cleaned or None+++def build_backtest_sql(*, window_days: int, limit: int, source: str | None) -> str:+ """Bounded SELECT over the lake for the backtest window (tenant filter is+ injected later by ``lake_sql.rewrite_for_tenant``)."""+ window_days = max(1, min(int(window_days), 365))+ limit = max(1, min(int(limit), 100_000))+ clauses = [f"event_time >= now() - INTERVAL {window_days} DAY"]+ safe_source = sanitize_source(source)+ if safe_source:+ clauses.append(f"connector_type = '{safe_source}'")+ where = " AND ".join(clauses)+ return f"SELECT * FROM aisoc.raw_events WHERE {where} ORDER BY event_time DESC LIMIT {limit}"+++def rows_to_events(columns: list[str], rows: list[list[Any]]) -> list[dict[str, Any]]:+ """Zip lake columns+rows into event dicts, expanding any JSON payload column+ (``raw_data`` / ``raw_event``) so rules that match connector-flat fields work."""+ events: list[dict[str, Any]] = []+ for row in rows:+ event = dict(zip(columns, row, strict=False))+ for payload_key in ("raw_data", "raw_event"):+ payload = event.get(payload_key)+ if isinstance(payload, str) and payload.strip():+ try:+ parsed = json.loads(payload)+ if isinstance(parsed, dict):+ # Flat payload fields take precedence for matching, but+ # keep the OCSF columns available too.+ event = {**event, **parsed}+ except (ValueError, TypeError):+ pass+ elif isinstance(payload, dict):+ event = {**event, **payload}+ events.append(event)+ return events+++def backtest_rule(+ *,+ rule_language: str,+ rule_body: str,+ events: list[dict[str, Any]],+ sample_limit: int = 20,+) -> dict[str, Any]:+ """Run a rule over historical events; return an exact would-fire summary."""+ matched, error = evaluate_rule_over_events(rule_language, rule_body, events)+ scanned = len(events)+ fired = len(matched)+ return {+ "events_scanned": scanned,+ "would_fire": fired,+ "hit_rate": round(fired / scanned, 4) if scanned else 0.0,+ "sample_matches": matched[:sample_limit],+ "error": error,+ }diff --git a/services/api/app/services/rule_engine.py b/services/api/app/services/rule_engine.pyindex c08a12c73..191dfee3c 100644--- a/services/api/app/services/rule_engine.py+++ b/services/api/app/services/rule_engine.py@@ -422,6 +422,35 @@ def _flatten_dict(d: dict[str, Any], prefix: str = "") -> dict[str, Any]:# ─── Main Execute Function ────────────────────────────────────────────────────+def _rule_runners():+ """Language -> runner map shared by execute_rule + backtest."""+ return {+ "sigma": _run_sigma,+ "yara": _run_yara,+ "kql": _run_kql,+ "eql": _run_eql,+ "lucene": lambda body, evts: (_run_kql(body, evts)[0], None),+ "regex": _run_regex,+ }+++def evaluate_rule_over_events(+ rule_language: str,+ rule_body: str,+ events: list[dict[str, Any]],+) -> tuple[list[dict[str, Any]], str | None]:+ """Return (ALL matched events, error) for a rule over events.++ Unlike :func:`execute_rule` (which returns a bool + caps samples at 10),+ this exposes the full match list so a backtest can report an exact count of+ how many historical events a candidate rule would have fired on.+ """+ runner = _rule_runners().get(rule_language.lower())+ if runner is None:+ return [], f"Unsupported rule language: {rule_language}"+ return runner(rule_body, events)++def execute_rule(rule_id: str,rule_name: str,@@ -437,14 +466,7 @@ def execute_rule(start = time.monotonic()lang = rule_language.lower()- runners = {- "sigma": _run_sigma,- "yara": _run_yara,- "kql": _run_kql,- "eql": _run_eql,- "lucene": lambda body, evts: (_run_kql(body, evts)[0], None),- "regex": _run_regex,- }+ runners = _rule_runners()runner = runners.get(lang)if runner is None:diff --git a/services/api/tests/test_backtest.py b/services/api/tests/test_backtest.pynew file mode 100644index 000000000..bfc5831b2--- /dev/null+++ b/services/api/tests/test_backtest.py@@ -0,0 +1,68 @@+"""Wave 2 - detection backtesting over the lake (pure logic).++The lake-fetch path needs a live ClickHouse and is covered by the integration+gate; these tests pin the pure, deterministic pieces: bounded/allow-listed SQL+construction, row->event mapping (with JSON payload expansion), and the+would-fire count/hit-rate/sample summary.+"""++from __future__ import annotations++from app.services.backtest import (+ backtest_rule,+ build_backtest_sql,+ rows_to_events,+ sanitize_source,+)+++def test_build_backtest_sql_bounds_and_source():+ sql = build_backtest_sql(window_days=30, limit=5000, source="okta_system_log")+ assert "FROM aisoc.raw_events" in sql+ assert "INTERVAL 30 DAY" in sql+ assert "connector_type = 'okta_system_log'" in sql+ assert "LIMIT 5000" in sql+ # window + limit are clamped to sane maxima+ assert "INTERVAL 365 DAY" in build_backtest_sql(window_days=9999, limit=1, source=None)+ assert "LIMIT 100000" in build_backtest_sql(window_days=1, limit=10**9, source=None)+++def test_source_filter_is_injection_sanitised():+ sql = build_backtest_sql(window_days=1, limit=1, source="okta'; DROP TABLE x;--")+ assert "DROP TABLE" not in sql+ assert sanitize_source("Okta_System-Log.1") == "okta_system-log.1"+ assert sanitize_source("'; drop") == "drop"+ assert sanitize_source("!!!") is None+ assert sanitize_source(None) is None+++def test_rows_to_events_zip_and_expand_payload():+ cols = ["event_id", "connector_type", "raw_data"]+ rows = [["e1", "okta", '{"user": "ceo", "action": "login"}']]+ events = rows_to_events(cols, rows)+ assert events[0]["connector_type"] == "okta"+ assert events[0]["user"] == "ceo" # expanded from the JSON payload column+ assert events[0]["action"] == "login"+++def test_backtest_rule_counts_hit_rate_and_samples():+ events = [{"msg": "malware detected"}, {"msg": "benign login"}, {"msg": "more malware here"}]+ result = backtest_rule(rule_language="regex", rule_body="malware", events=events, sample_limit=1)+ assert result["events_scanned"] == 3+ assert result["would_fire"] == 2+ assert result["hit_rate"] == round(2 / 3, 4)+ assert len(result["sample_matches"]) == 1 # capped to sample_limit+ assert result["error"] is None+++def test_backtest_unsupported_language_reports_error_no_fire():+ result = backtest_rule(rule_language="esql", rule_body="x", events=[{"a": 1}])+ assert result["would_fire"] == 0+ assert result["error"] is not None+++def test_backtest_empty_lake_is_zero_not_crash():+ result = backtest_rule(rule_language="regex", rule_body="anything", events=[])+ assert result["events_scanned"] == 0+ assert result["would_fire"] == 0+ assert result["hit_rate"] == 0.0