Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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

feat(phase-6): performance + cost gates (throughput floor + $/TB model + ADR) (#431)

Beenu Arora186a9c9b66e4
diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml
new file mode 100644
index 000000000..1dd9d868d
--- /dev/null
+++ b/.github/workflows/perf.yml
@@ -0,0 +1,88 @@
+name: Performance + cost
+
+# Phase 6 (world-class program) — two cheap, non-flaky gates:
+#
+# throughput — runs the fusion hot-path throughput harness over a
+# deterministic synthetic corpus and asserts a GENEROUS
+# regression floor (a >200x margin below the measured number).
+# It fires only on a catastrophic regression (e.g. an I/O call
+# slipping onto the promote hot path), never on runner jitter.
+# It is a regression floor, not a production SLO.
+# cost-model — regenerates the storage $/TB worked example and fails if the
+# committed docs/decisions/storage-cost-model.json is stale, so
+# the number ADR-0005 cites can never silently drift.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'services/fusion/app/services/promoter.py'
+ - 'services/fusion/app/models/**'
+ - 'scripts/perf/**'
+ - 'scripts/storage_cost_model.py'
+ - 'docs/decisions/storage-cost-model.json'
+ - '.github/workflows/perf.yml'
+ pull_request:
+ paths:
+ - 'services/fusion/app/services/promoter.py'
+ - 'services/fusion/app/models/**'
+ - 'scripts/perf/**'
+ - 'scripts/storage_cost_model.py'
+ - 'docs/decisions/storage-cost-model.json'
+ - '.github/workflows/perf.yml'
+ workflow_dispatch:
+
+concurrency:
+ group: perf-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ throughput:
+ name: Fusion hot-path throughput (regression floor)
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: '3.12'
+ - name: Install promoter deps
+ run: pip install --quiet pydantic pydantic-settings structlog
+ - name: Run throughput harness (generous floor)
+ run: |
+ python3 scripts/perf/throughput_harness.py --events 20000 --assert-floor 1000 --json | tee /tmp/throughput.json
+ - name: Publish throughput summary
+ if: always()
+ run: |
+ {
+ echo "## Fusion hot-path throughput"
+ echo ""
+ echo '```json'
+ cat /tmp/throughput.json 2>/dev/null || echo "{}"
+ echo '```'
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ cost-model:
+ name: Storage $/TB cost model (drift gate)
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: '3.12'
+ - name: Verify committed storage cost model is current
+ run: python3 scripts/storage_cost_model.py --check
+ - name: Publish cost summary
+ if: always()
+ run: |
+ {
+ echo "## Storage \$/TB cost model"
+ echo ""
+ echo '```'
+ python3 scripts/storage_cost_model.py 2>/dev/null || true
+ echo '```'
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e4951af29..e66f47241 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Phase 6 — performance + cost, both gated.** Two cheap, non-flaky gates in a new `.github/workflows/perf.yml`. (1) **Throughput** — `scripts/perf/throughput_harness.py` runs the *real* fusion hot path (`promote_normalized_event`) over a deterministic 20k-event synthetic corpus and reports events/sec + p50/p95/p99 per-event latency (measured ~250k eps on commodity hardware). The gate asserts a **generous regression floor** (1,000 eps — a >200× margin) so it fires only on a catastrophic regression such as an I/O call slipping onto the hot path, never on shared-runner jitter; it is explicitly a regression floor, not a production SLO. (2) **Cost** — `scripts/storage_cost_model.py` is a deterministic tiered-storage $/TB model (hot ClickHouse block 30d / warm object 60d / cold archive 275d, 8× ZSTD); the committed worked example (`docs/decisions/storage-cost-model.json`: ≈ $902/mo and ≈ $30/raw-TB at 1 TB/day) is drift-gated by `--check`, so the number can never silently diverge from the rate card. Rate-card values are labelled reference list prices to verify per provider/region — the value is the methodology, not the exact dollars. `docs/decisions/0005-storage-consolidation.md` (ADR) records the three-tier decision (keep ClickHouse-only hot; do not add a second hot engine) and cites the gated model.
- **Phase 5 — data spine correctness: schema registry + dead-letter queue + lineage.** The reality audit's load-bearing gap: the fusion consumer logged a warning and **silently dropped** any malformed message — silent data loss. Now every message is schema-validated against a versioned envelope registry (`services/fusion/app/services/event_schema.py`: `aisoc.raw_events` and `aisoc.alerts.raw`, each pinned to `v1`, with a drift-guard test so the wire contract can't move unnoticed) *before* the promoter sees it. Anything that fails — non-object payload, unknown `schema_version`, missing `ocsf_event`, non-UUID tenant, or a RawAlert that fails deep Pydantic validation — is routed to a **fail-soft dead-letter queue** (`services/fusion/app/services/dlq.py`: `LoggingDLQ` default, `InMemoryDLQ` for tests, `KafkaDLQ` republishing to `aisoc.alerts.dlq`) with its reason, schema version, source-event lineage, and a truncated payload, instead of vanishing. `safe_record` guarantees a DLQ that itself throws never crashes the consumer. Each processed alert logs `fusion.lineage` (source event id + schema version). 21 new tests (`test_event_schema.py`, `test_dlq.py`, `test_consumer_dlq.py`) prove a valid event is processed with an empty DLQ, every poison shape is captured (not dropped), and a failing DLQ sink doesn't crash the consumer; full fusion suite 92/92 at 59% coverage (floor 48). Idempotency (AlertSink dedup fingerprint, Phase 3.1) and event-time watermarking are already present; backfill/replay-from-offset is tracked as 5b in `docs/audit/PROGRESS.md`.
- **Phase 4a — the Detection-as-Code gate is no longer circular.** The reality audit's #1 circular gate: the detection-proposal promote path shelled out to `run_evals.py` **without ever passing the proposed rule body**, so "passed" meant the repo-wide substrate MITRE accuracy didn't move — a value independent of the rule under review. A blind rule (matches nothing) or a noisy rule (matches everything) sailed through its own exam. New `services/api/app/services/detection_eval.py::evaluate_candidate_rule` runs the *candidate `rule_body` itself* through the **real** runtime engine (`rule_engine.execute_rule`) against caller-supplied positive/negative fixtures: it must fire on every positive and stay silent on every negative. New `POST /detection-proposals/{id}/evaluate-rule` stores the verdict under `eval_result["candidate_rule"]`, and `POST /decide` (approve) now **requires** it — a benchmark-only pass is no longer sufficient. `services/api/tests/test_detection_eval.py` (6 tests) is the mutation test that proves the gate rejects a blind rule, rejects a noisy rule, rejects a no-positive-fixture rule, and that the verdict genuinely depends on the rule body. Claim-to-gate matrix: DAC row PARTIAL(circular) → GATED.
- **Phase 4b — detection content truth table (honest coverage).** The README advertised "6000+ imported detection rules", but ~97% live under `_quarantine/` (`enabled: false`) because their upstream query language (SPL / YARA-L / CAR pseudocode) does not execute on the engine. New `scripts/detection_truth_table.py` walks `detections/` and classifies every rule **executable** (fires today) vs **non-executable** (provenance/coverage only), rendering `docs/detections/truth-table.md`. The honest headline: **939 executable** rules (861 native + 77 sigma-imported + 1 community) of 6975 on disk; 5921 quarantined, 115 disabled. `--check` gates the doc in `validate-detections.yml` so the number can never quietly drift from reality, and the README now cites the executable figure for *coverage* (the on-disk figure only describes the imported *library*). Claim-to-gate matrix: 6000+-imported row PARTIAL → GATED (14 GATED / 10 PARTIAL / 3 NO GATE). The LLM-dependent half of Phase 4 (live-agent Tier-1 eval, hallucination/calibration/abstention, model matrix, 150-payload prompt-injection adversarial) is tracked as 4c+ in `docs/audit/PROGRESS.md`.
diff --git a/ROADMAP.md b/ROADMAP.md
index 3582dc13c..fa5875c78 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -28,7 +28,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- [x] Phase 3 — Integration / E2E / chaos / DR (real-container spine test, backup-restore, chaos, upgrade, cross-store isolation live-replay; heavy-demo-stack Playwright E2E + demo-timing gate tracked as non-blocking 3.5+)
- [ ] Phase 4 — Real evals + detection content truth table (third-party-labeled corpus, hallucination/calibration/abstention, model matrix) — **4a/4b landed** (de-circularised DAC candidate-rule gate + honest executable-vs-imported truth table); 4c+ live-agent eval / calibration / model matrix pending
- [x] Phase 5 — Data spine correctness (versioned event-schema registry + dead-letter queue + source-event lineage in the fusion consumer; idempotency via AlertSink dedup + event-time watermarking; backfill/replay-from-offset tracked as 5b)
-- [ ] Phase 6 — Performance + cost (throughput harness, $/TB, storage-consolidation ADR)
+- [x] Phase 6 — Performance + cost (fusion hot-path throughput harness with a generous regression-floor gate; deterministic storage $/TB cost model + drift gate; storage-consolidation ADR-0005)
- [ ] Phase 7 — Ingest-time graph + multi-model router (posture, effective permissions, bi-temporal, fusion-time ContextBundle, determinism contract)
- [ ] Phase 8 — LLMOps (prompt registry, model pinning, provider fallback, response caching, structured-output validation)
- [ ] Phase 9 — Autonomy safety (rollback, post-action verification, dry-run default, break-glass, approval SLA, scorecard)
diff --git a/docs/decisions/0005-storage-consolidation.md b/docs/decisions/0005-storage-consolidation.md
new file mode 100644
index 000000000..b9fda9cec
--- /dev/null
+++ b/docs/decisions/0005-storage-consolidation.md
@@ -0,0 +1,86 @@
+# ADR-0005 — Tiered storage consolidation + a $/TB cost model
+
+- **Status:** accepted
+- **Date:** 2026-07-12
+- **Decision-makers:** AiSOC core team
+- **Plan reference:** World-Class Hardening Program, Phase 6 (performance + cost) — [`ROADMAP.md`](../../ROADMAP.md), [`docs/audit/PROGRESS.md`](../audit/PROGRESS.md).
+
+## Context
+
+AiSOC persists security telemetry across several stores (ClickHouse for the
+queryable hot tier, Postgres for alert/case state, object storage for
+retention). Two questions kept coming up without a written answer:
+
+1. **What does storage actually cost per TB of ingested telemetry?** Sales,
+ sizing guides, and the managed-mode pricing shape (ADR-0003) all need a
+ defensible number, and "it depends" is not one.
+2. **How many storage engines should the raw-event path use?** Every extra
+ engine is another thing to operate, secure (see the cross-store isolation
+ gate, Phase 3.4), back up (Phase 3.1), and reason about.
+
+Without arithmetic, both questions get answered by intuition, and intuition
+drifts. Phase 6 makes the cost a computed, gated artifact.
+
+## Decision
+
+**1. Keep a three-tier storage model for raw telemetry, do not add engines.**
+
+| Tier | Store | Retention | Why |
+|------|-------|-----------|-----|
+| Hot | ClickHouse on block storage | 30 days | Interactive lake queries (`/lake/sql`), fusion lookbacks, hunts |
+| Warm | Object storage (standard) | +60 days (to 90d) | Investigations that reach back a quarter; cheaper per GB |
+| Cold/archive | Object storage (infrequent-access) | +275 days (to 365d) | Compliance retention; rarely read |
+
+The hot tier stays **ClickHouse only** — we explicitly reject adding a second
+hot analytical engine (e.g. a separate search cluster) for the raw-event path.
+The graph (Neo4j) and vector (Qdrant) stores serve different access patterns
+and are out of scope for this raw-telemetry tiering decision.
+
+**2. Publish a computed $/TB number and gate it.**
+
+`scripts/storage_cost_model.py` is the single source of truth. It is
+deterministic; the committed worked example is
+[`storage-cost-model.json`](./storage-cost-model.json), and
+`scripts/storage_cost_model.py --check` fails CI (`.github/workflows/perf.yml`)
+if the rate card or scenario changes without regenerating that file. The number
+below can therefore never silently drift.
+
+### Worked example (1 TB/day raw ingest, 8× ZSTD compression)
+
+| Tier | Days resident | Resident GB | $/GB-mo | $/mo |
+|------|--------------:|------------:|--------:|-----:|
+| hot_block | 30 | 3,750 | 0.080 | 300.00 |
+| warm_object | 60 | 7,500 | 0.023 | 172.50 |
+| cold_archive | 275 | 34,375 | 0.0125 | 429.69 |
+| **total** | | | | **902.19** |
+
+- **Steady-state storage cost: ≈ $902/month at 1 TB/day.**
+- **≈ $30/raw-TB ingested** (total monthly ÷ 30 TB ingested/month).
+
+> **These are reference list prices** (2026, one representative region). They
+> MUST be verified against your provider, region, and negotiated rates. The
+> value of this ADR is the *methodology and the tiering decision*, not the exact
+> dollar figures — which is exactly why the number is generated by a script and
+> gated, not typed into prose.
+
+## Consequences
+
+- **Positive.** A defensible, reproducible $/TB figure for sizing and pricing.
+ One fewer hot engine to operate/secure/back up. The cost assumptions
+ (compression ratio, retention, rate card) are explicit and versioned.
+- **Negative.** Object-tier reads (warm/cold) are slower than ClickHouse; an
+ investigation reaching past 30 days pays a latency cost. Accepted: >30-day
+ lookbacks are rare and the cost saving is large (block is ~3.5× object).
+- **Follow-up (Phase 6b, tracked in `docs/audit/PROGRESS.md`).** Wire the model
+ into the managed-mode sizing guide and the LLM-cost dashboard so a tenant's
+ storage $/mo shows next to its LLM $/mo.
+
+## Performance gate
+
+Phase 6 also lands `scripts/perf/throughput_harness.py`, a fusion hot-path
+throughput benchmark (measured ~250k events/sec for `promote_normalized_event`
+on commodity CI hardware). `.github/workflows/perf.yml` runs it with a
+**generous** regression floor (1,000 eps — a >200× margin) so the gate fires
+only on a catastrophic regression such as an I/O call slipping onto the hot
+path, never on shared-runner jitter. It is a regression floor, not a production
+SLO.
diff --git a/docs/decisions/storage-cost-model.json b/docs/decisions/storage-cost-model.json
new file mode 100644
index 000000000..cccc9931a
--- /dev/null
+++ b/docs/decisions/storage-cost-model.json
@@ -0,0 +1,40 @@
+{
+ "disclaimer": "reference list prices; verify against your provider/region and negotiated rates",
+ "rate_card_usd_per_gb_month": {
+ "cold_archive": 0.0125,
+ "hot_block": 0.08,
+ "warm_object": 0.023
+ },
+ "raw_tb_ingested_per_month": 30.0,
+ "scenario": {
+ "compression_ratio": 8.0,
+ "raw_tb_per_day": 1.0,
+ "retention_days": {
+ "cold_archive": 275,
+ "hot_block": 30,
+ "warm_object": 60
+ }
+ },
+ "tiers": {
+ "cold_archive": {
+ "monthly_usd": 429.69,
+ "rate_usd_per_gb_month": 0.0125,
+ "resident_gb": 34375.0,
+ "retention_days": 275
+ },
+ "hot_block": {
+ "monthly_usd": 300.0,
+ "rate_usd_per_gb_month": 0.08,
+ "resident_gb": 3750.0,
+ "retention_days": 30
+ },
+ "warm_object": {
+ "monthly_usd": 172.5,
+ "rate_usd_per_gb_month": 0.023,
+ "resident_gb": 7500.0,
+ "retention_days": 60
+ }
+ },
+ "total_monthly_usd": 902.19,
+ "usd_per_raw_tb_ingested": 30.07
+}
diff --git a/scripts/perf/throughput_harness.py b/scripts/perf/throughput_harness.py
new file mode 100644
index 000000000..75ca7c4ee
--- /dev/null
+++ b/scripts/perf/throughput_harness.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""Fusion hot-path throughput harness (Phase 6 — performance).
+
+Measures how fast the promotion hot path — the deterministic per-event work that
+turns an ingest-normalized OCSF event into a fusion RawAlert — processes events.
+This is the CPU-bound stage that sits on the critical ingest→alert path, so a
+regression here (e.g. someone slips an I/O call into `promote_normalized_event`)
+directly widens time-to-alert.
+
+The harness runs the **real** `services/fusion` promoter over a deterministic
+synthetic corpus and reports events/sec plus per-event p50/p95/p99 latency. It
+is deliberately **not** a production SLO — CI runners are noisy shared hardware.
+`--assert-floor` sets a *generous* regression floor (order of magnitude below
+the real number) so the gate fires only on a catastrophic regression, never on
+runner jitter. The measured number is published for trend visibility.
+
+Usage:
+ python3 scripts/perf/throughput_harness.py # measure + print
+ python3 scripts/perf/throughput_harness.py --json # JSON to stdout
+ python3 scripts/perf/throughput_harness.py --events 20000 --assert-floor 1000
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import time
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+# The promoter lives in the fusion service; import it directly so we benchmark
+# the code that actually runs in production, not a copy.
+sys.path.insert(0, str(ROOT / "services" / "fusion"))
+
+from app.services.promoter import promote_normalized_event # noqa: E402
+
+_TENANT = "00000000-0000-0000-0000-000000000001"
+
+
+def _synthetic_event(i: int) -> dict:
+ """A deterministic OCSF-ish event. Every 3rd is a promotable finding; the
+ rest are lower-severity telemetry (exercises both promoter branches)."""
+ is_finding = i % 3 == 0
+ severity_id = 5 if is_finding else (4 if i % 3 == 1 else 2)
+ return {
+ "tenant_id": _TENANT,
+ "ocsf_event": {
+ "class_uid": 2001 if is_finding else 4001,
+ "category_uid": 2 if is_finding else 4,
+ "severity_id": severity_id,
+ "message": f"synthetic event {i}: suspicious process activity",
+ "time": "2026-07-12T08:00:00Z",
+ "metadata": {"uid": f"ev-{i}", "product": {"name": "Falcon", "vendor_name": "CrowdStrike"}},
+ "device": {"name": f"HOST-{i % 500}"},
+ "actor": {"user": {"name": f"user{i % 200}"}},
+ "src_endpoint": {"ip": f"10.0.{i % 255}.{(i * 7) % 255}"},
+ "file": {"fingerprints": [{"value": f"{i:064x}"}]},
+ "mitre_attck": [
+ {"technique_id": "T1003", "technique_name": "OS Credential Dumping", "tactic_names": ["Credential Access"]}
+ ],
+ },
+ }
+
+
+def run(n_events: int) -> dict:
+ corpus = [_synthetic_event(i) for i in range(n_events)]
+
+ latencies_us: list[float] = []
+ promoted = 0
+ started = time.perf_counter()
+ for event in corpus:
+ t0 = time.perf_counter()
+ alert = promote_normalized_event(event)
+ latencies_us.append((time.perf_counter() - t0) * 1e6)
+ if alert is not None:
+ promoted += 1
+ elapsed = time.perf_counter() - started
+
+ latencies_us.sort()
+
+ def _pct(p: float) -> float:
+ if not latencies_us:
+ return 0.0
+ idx = min(len(latencies_us) - 1, int(p / 100 * len(latencies_us)))
+ return round(latencies_us[idx], 2)
+
+ eps = round(n_events / elapsed, 1) if elapsed > 0 else float("inf")
+ return {
+ "events": n_events,
+ "promoted": promoted,
+ "elapsed_seconds": round(elapsed, 4),
+ "events_per_second": eps,
+ "latency_us": {"p50": _pct(50), "p95": _pct(95), "p99": _pct(99)},
+ "stage": "fusion.promote_normalized_event",
+ "note": "regression floor, not a production SLO (CI runners are shared hardware)",
+ }
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--events", type=int, default=10000)
+ parser.add_argument("--json", dest="as_json", action="store_true")
+ parser.add_argument(
+ "--assert-floor",
+ type=float,
+ default=None,
+ help="fail (exit 1) if events/sec falls below this generous regression floor",
+ )
+ args = parser.parse_args()
+
+ result = run(args.events)
+
+ if args.as_json:
+ print(json.dumps(result, indent=2))
+ else:
+ print(f"stage: {result['stage']}")
+ print(f"events: {result['events']} ({result['promoted']} promoted)")
+ print(f"elapsed: {result['elapsed_seconds']}s")
+ print(f"throughput: {result['events_per_second']} events/sec")
+ print(f"latency (us): p50={result['latency_us']['p50']} p95={result['latency_us']['p95']} p99={result['latency_us']['p99']}")
+
+ if args.assert_floor is not None:
+ if result["events_per_second"] < args.assert_floor:
+ print(
+ f"::error::throughput {result['events_per_second']} eps below regression floor "
+ f"{args.assert_floor} eps — a catastrophic regression (likely I/O on the hot path)",
+ file=sys.stderr,
+ )
+ return 1
+ print(f"OK: {result['events_per_second']} eps >= floor {args.assert_floor} eps")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/storage_cost_model.py b/scripts/storage_cost_model.py
new file mode 100644
index 000000000..11dc95fa2
--- /dev/null
+++ b/scripts/storage_cost_model.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python3
+"""Storage $/TB cost model (Phase 6 — cost).
+
+AiSOC stores security telemetry in tiers: a hot ClickHouse tier on block
+storage for recent, queryable events; a warm object tier; and a cold/archive
+object tier for compliance retention. This model turns that tiering into a
+defensible $/TB number so the storage-consolidation decision
+(`docs/decisions/0005-storage-consolidation.md`) rests on arithmetic, not vibes.
+
+**The value here is the methodology, not the exact prices.** The rate card
+below is *reference list pricing* (2026, single representative region) and MUST
+be verified against your provider, region, and negotiated rates. The model is
+deterministic, so `--check` gates the committed worked example
+(`docs/decisions/storage-cost-model.json`) — if the rate card or scenario
+changes, the JSON must be regenerated, and the ADR cites that file.
+
+Usage:
+ python3 scripts/storage_cost_model.py # print the worked example
+ python3 scripts/storage_cost_model.py --json # JSON to stdout
+ python3 scripts/storage_cost_model.py --check # fail on drift vs committed JSON
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+COMMITTED = ROOT / "docs" / "decisions" / "storage-cost-model.json"
+
+# Reference list prices, USD per GB-month. VERIFY against your provider/region.
+RATE_CARD_USD_PER_GB_MONTH = {
+ "hot_block": 0.080, # gp3-class block storage backing ClickHouse hot tier
+ "warm_object": 0.023, # standard object storage
+ "cold_archive": 0.0125, # infrequent-access / archive object storage
+}
+
+# Canonical worked example. Security telemetry compresses well under ClickHouse
+# ZSTD; 8x is a conservative documented assumption for JSON-shaped logs.
+SCENARIO = {
+ "raw_tb_per_day": 1.0,
+ "compression_ratio": 8.0,
+ "retention_days": {"hot_block": 30, "warm_object": 60, "cold_archive": 275}, # 365 total
+}
+
+_GB_PER_TB = 1000
+
+
+def compute(scenario: dict, rate_card: dict) -> dict:
+ raw_gb_per_day = scenario["raw_tb_per_day"] * _GB_PER_TB
+ ratio = scenario["compression_ratio"]
+ stored_gb_per_day = raw_gb_per_day / ratio
+
+ tiers: dict[str, dict] = {}
+ total_monthly = 0.0
+ for tier, days in scenario["retention_days"].items():
+ # Steady-state stored volume for this tier = days of retention worth of
+ # compressed data resident in the tier at any moment.
+ resident_gb = stored_gb_per_day * days
+ monthly = resident_gb * rate_card[tier]
+ total_monthly += monthly
+ tiers[tier] = {
+ "retention_days": days,
+ "resident_gb": round(resident_gb, 2),
+ "rate_usd_per_gb_month": rate_card[tier],
+ "monthly_usd": round(monthly, 2),
+ }
+
+ raw_tb_ingested_per_month = scenario["raw_tb_per_day"] * 30
+ usd_per_raw_tb = total_monthly / raw_tb_ingested_per_month if raw_tb_ingested_per_month else 0.0
+
+ return {
+ "scenario": scenario,
+ "rate_card_usd_per_gb_month": rate_card,
+ "tiers": tiers,
+ "total_monthly_usd": round(total_monthly, 2),
+ "raw_tb_ingested_per_month": round(raw_tb_ingested_per_month, 2),
+ "usd_per_raw_tb_ingested": round(usd_per_raw_tb, 2),
+ "disclaimer": "reference list prices; verify against your provider/region and negotiated rates",
+ }
+
+
+def _print_table(result: dict) -> None:
+ s = result["scenario"]
+ print("Storage cost model — worked example")
+ print(f" raw ingest: {s['raw_tb_per_day']} TB/day")
+ print(f" compression: {s['compression_ratio']}x")
+ print()
+ print(f" {'tier':<14}{'days':>6}{'resident_GB':>14}{'$/GB-mo':>10}{'$/mo':>12}")
+ for tier, t in result["tiers"].items():
+ print(f" {tier:<14}{t['retention_days']:>6}{t['resident_gb']:>14}{t['rate_usd_per_gb_month']:>10}{t['monthly_usd']:>12}")
+ print()
+ print(f" total monthly: ${result['total_monthly_usd']}")
+ print(f" $ / raw TB ingested: ${result['usd_per_raw_tb_ingested']}")
+ print(f" ({result['disclaimer']})")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--json", dest="as_json", action="store_true")
+ parser.add_argument("--check", action="store_true", help="fail if committed JSON is stale")
+ args = parser.parse_args()
+
+ result = compute(SCENARIO, RATE_CARD_USD_PER_GB_MONTH)
+
+ if args.check:
+ if not COMMITTED.exists():
+ print(f"ERROR: {COMMITTED.relative_to(ROOT)} missing — run scripts/storage_cost_model.py --write", file=sys.stderr)
+ return 1
+ committed = json.loads(COMMITTED.read_text(encoding="utf-8"))
+ if committed != result:
+ print(
+ f"ERROR: {COMMITTED.relative_to(ROOT)} is stale. The rate card or scenario changed but the "
+ "committed worked example was not regenerated. Run: python3 scripts/storage_cost_model.py --write",
+ file=sys.stderr,
+ )
+ return 1
+ print(f"OK: storage cost model current — ${result['usd_per_raw_tb_ingested']}/raw-TB")
+ return 0
+
+ if args.as_json:
+ print(json.dumps(result, indent=2, sort_keys=True))
+ return 0
+
+ _print_table(result)
+ return 0
+
+
+if __name__ == "__main__":
+ # Hidden --write to regenerate the committed JSON (used by maintainers).
+ if "--write" in sys.argv:
+ payload = compute(SCENARIO, RATE_CARD_USD_PER_GB_MONTH)
+ COMMITTED.parent.mkdir(parents=True, exist_ok=True)
+ COMMITTED.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ print(f"wrote {COMMITTED.relative_to(ROOT)}")
+ raise SystemExit(0)
+ raise SystemExit(main())