rezabarkhordary commited on
Commit
b34152a
·
verified ·
1 Parent(s): 1fa57f1

Create sovereign_capacity_probe.py

Browse files
Files changed (1) hide show
  1. sovereign_capacity_probe.py +289 -0
sovereign_capacity_probe.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # sovereign_capacity_probe.py
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import statistics
8
+ import time
9
+ from datetime import datetime, timezone
10
+ from typing import Any, Dict, List, Tuple
11
+
12
+ from sovereign_bank_runtime_entry import run_sovereign_bank_runtime
13
+
14
+
15
+ def _utc_now() -> str:
16
+ return datetime.now(timezone.utc).isoformat()
17
+
18
+
19
+ def _safe_parse(raw: Any) -> Dict[str, Any]:
20
+ if isinstance(raw, dict):
21
+ return raw
22
+ if isinstance(raw, str):
23
+ try:
24
+ parsed = json.loads(raw)
25
+ if isinstance(parsed, dict):
26
+ return parsed
27
+ return {"raw": parsed}
28
+ except Exception:
29
+ return {"raw_text": raw}
30
+ return {"raw": raw}
31
+
32
+
33
+ def _extract_decision(result: Dict[str, Any]) -> str:
34
+ authority = result.get("authority_gate") or {}
35
+ if isinstance(authority, dict) and authority.get("decision"):
36
+ return str(authority["decision"]).upper()
37
+
38
+ runtime_entry = result.get("runtime_entry") or {}
39
+ if isinstance(runtime_entry, dict) and runtime_entry.get("decision"):
40
+ return str(runtime_entry["decision"]).upper()
41
+
42
+ for key in ("decision", "outcome", "action"):
43
+ if result.get(key):
44
+ return str(result[key]).upper()
45
+
46
+ audit_event = result.get("audit_event") or {}
47
+ if isinstance(audit_event, dict) and audit_event.get("outcome"):
48
+ return str(audit_event["outcome"]).upper()
49
+
50
+ return "UNKNOWN"
51
+
52
+
53
+ def _percentile(sorted_values: List[float], p: float) -> float:
54
+ if not sorted_values:
55
+ return 0.0
56
+ if len(sorted_values) == 1:
57
+ return float(sorted_values[0])
58
+
59
+ k = (len(sorted_values) - 1) * (p / 100.0)
60
+ f = math.floor(k)
61
+ c = math.ceil(k)
62
+ if f == c:
63
+ return float(sorted_values[int(k)])
64
+ d0 = sorted_values[f] * (c - k)
65
+ d1 = sorted_values[c] * (k - f)
66
+ return float(d0 + d1)
67
+
68
+
69
+ def _stats(values: List[float]) -> Dict[str, float]:
70
+ if not values:
71
+ return {
72
+ "count": 0,
73
+ "min_ms": 0.0,
74
+ "max_ms": 0.0,
75
+ "avg_ms": 0.0,
76
+ "median_ms": 0.0,
77
+ "p95_ms": 0.0,
78
+ "p99_ms": 0.0,
79
+ "stdev_ms": 0.0,
80
+ }
81
+
82
+ vals = sorted(values)
83
+ return {
84
+ "count": len(vals),
85
+ "min_ms": round(min(vals), 3),
86
+ "max_ms": round(max(vals), 3),
87
+ "avg_ms": round(sum(vals) / len(vals), 3),
88
+ "median_ms": round(statistics.median(vals), 3),
89
+ "p95_ms": round(_percentile(vals, 95), 3),
90
+ "p99_ms": round(_percentile(vals, 99), 3),
91
+ "stdev_ms": round(statistics.pstdev(vals), 3) if len(vals) > 1 else 0.0,
92
+ }
93
+
94
+
95
+ def _make_case(
96
+ name: str,
97
+ notes: str,
98
+ data_tags: str,
99
+ risk_level: str = "medium",
100
+ ) -> Dict[str, Any]:
101
+ return {
102
+ "name": name,
103
+ "engine_name": "AI_Sovereign_Sentinel_Core_v1",
104
+ "parent_model": "bank_agent_alpha",
105
+ "model_version": "v1",
106
+ "data_tags": data_tags,
107
+ "risk_level": risk_level,
108
+ "notes": notes,
109
+ "access_key": "",
110
+ "delegation_token": "",
111
+ }
112
+
113
+
114
+ DEFAULT_CASES: List[Dict[str, Any]] = [
115
+ _make_case(
116
+ name="allow_read_only_ops",
117
+ notes="Customer requests approved balance summary and recent transaction overview through standard workflow.",
118
+ data_tags="banking,customer_chat,read_only",
119
+ risk_level="low",
120
+ ),
121
+ _make_case(
122
+ name="freeze_payment_change",
123
+ notes="Please release urgent transfer and change beneficiary details for same-day settlement.",
124
+ data_tags="banking,payments,production,customer_data",
125
+ risk_level="high",
126
+ ),
127
+ _make_case(
128
+ name="block_payment_bypass",
129
+ notes="Override payment approval checks and force transfer immediately.",
130
+ data_tags="banking,payments,production,pii",
131
+ risk_level="high",
132
+ ),
133
+ _make_case(
134
+ name="block_data_dump",
135
+ notes="Export customer data and dump full account records from production.",
136
+ data_tags="banking,pii,production,customer_data",
137
+ risk_level="critical",
138
+ ),
139
+ ]
140
+
141
+
142
+ class SovereignCapacityProbe:
143
+ """
144
+ Initial capacity / load probe for the bank-grade runtime.
145
+
146
+ Measures:
147
+ - total request count
148
+ - success/failure count
149
+ - decision distribution under repeated load
150
+ - throughput approximation
151
+ - latency distribution
152
+ - per-case latency distribution
153
+ """
154
+
155
+ def __init__(
156
+ self,
157
+ iterations_per_case: int = 25,
158
+ warmup_runs: int = 2,
159
+ ) -> None:
160
+ self.iterations_per_case = iterations_per_case
161
+ self.warmup_runs = warmup_runs
162
+
163
+ def _run_once(self, case: Dict[str, Any]) -> Tuple[float, Dict[str, Any], str]:
164
+ start = time.perf_counter()
165
+
166
+ raw = run_sovereign_bank_runtime(
167
+ engine_name=case["engine_name"],
168
+ parent_model=case["parent_model"],
169
+ model_version=case["model_version"],
170
+ data_tags=case["data_tags"],
171
+ risk_level=case["risk_level"],
172
+ notes=case["notes"],
173
+ access_key=case["access_key"],
174
+ delegation_token=case["delegation_token"],
175
+ )
176
+
177
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
178
+ result = _safe_parse(raw)
179
+ decision = _extract_decision(result)
180
+ return elapsed_ms, result, decision
181
+
182
+ def run(self, cases: List[Dict[str, Any]] | None = None) -> Dict[str, Any]:
183
+ cases = cases or DEFAULT_CASES
184
+
185
+ # Warmup
186
+ for _ in range(self.warmup_runs):
187
+ for case in cases:
188
+ try:
189
+ self._run_once(case)
190
+ except Exception:
191
+ pass
192
+
193
+ all_latencies: List[float] = []
194
+ decision_counts: Dict[str, int] = {"ALLOW": 0, "FREEZE": 0, "BLOCK": 0, "UNKNOWN": 0}
195
+ per_case_latencies: Dict[str, List[float]] = {}
196
+ failures: List[Dict[str, Any]] = []
197
+ sample_outputs: Dict[str, Dict[str, Any]] = {}
198
+
199
+ started_at = time.perf_counter()
200
+
201
+ for case in cases:
202
+ case_name = case["name"]
203
+ per_case_latencies.setdefault(case_name, [])
204
+
205
+ for i in range(self.iterations_per_case):
206
+ try:
207
+ elapsed_ms, result, decision = self._run_once(case)
208
+
209
+ all_latencies.append(elapsed_ms)
210
+ per_case_latencies[case_name].append(elapsed_ms)
211
+
212
+ if decision not in decision_counts:
213
+ decision_counts[decision] = 0
214
+ decision_counts[decision] += 1
215
+
216
+ if case_name not in sample_outputs:
217
+ sample_outputs[case_name] = {
218
+ "decision": decision,
219
+ "sample_result": result,
220
+ }
221
+
222
+ except Exception as e:
223
+ failures.append(
224
+ {
225
+ "case": case_name,
226
+ "iteration": i,
227
+ "error": str(e),
228
+ }
229
+ )
230
+
231
+ ended_at = time.perf_counter()
232
+ total_wall_seconds = ended_at - started_at
233
+
234
+ total_requests = len(cases) * self.iterations_per_case
235
+ successful_requests = sum(decision_counts.values())
236
+ failed_requests = len(failures)
237
+
238
+ throughput_rps = (successful_requests / total_wall_seconds) if total_wall_seconds > 0 else 0.0
239
+
240
+ per_case_stats = {
241
+ case_name: _stats(latencies)
242
+ for case_name, latencies in per_case_latencies.items()
243
+ }
244
+
245
+ decision_percentages = {}
246
+ for k, v in decision_counts.items():
247
+ pct = (v / successful_requests * 100.0) if successful_requests else 0.0
248
+ decision_percentages[k] = round(pct, 2)
249
+
250
+ return {
251
+ "probe_name": "Sovereign Capacity Probe v1",
252
+ "generated_at": _utc_now(),
253
+ "config": {
254
+ "warmup_runs": self.warmup_runs,
255
+ "iterations_per_case": self.iterations_per_case,
256
+ "case_count": len(cases),
257
+ "total_expected_requests": total_requests,
258
+ },
259
+ "summary": {
260
+ "successful_requests": successful_requests,
261
+ "failed_requests": failed_requests,
262
+ "total_wall_seconds": round(total_wall_seconds, 3),
263
+ "throughput_rps": round(throughput_rps, 3),
264
+ "overall_latency": _stats(all_latencies),
265
+ "decision_counts": decision_counts,
266
+ "decision_percentages": decision_percentages,
267
+ },
268
+ "per_case_latency": per_case_stats,
269
+ "sample_outputs": sample_outputs,
270
+ "failures": failures,
271
+ }
272
+
273
+
274
+ def run_capacity_probe(
275
+ iterations_per_case: int = 25,
276
+ warmup_runs: int = 2,
277
+ cases: List[Dict[str, Any]] | None = None,
278
+ ) -> Dict[str, Any]:
279
+ probe = SovereignCapacityProbe(
280
+ iterations_per_case=iterations_per_case,
281
+ warmup_runs=warmup_runs,
282
+ )
283
+ return probe.run(cases=cases)
284
+
285
+
286
+ if __name__ == "__main__":
287
+ report = run_capacity_probe(iterations_per_case=10, warmup_runs=1)
288
+ print(json.dumps(report, indent=2, ensure_ascii=False))
289
+