rezabarkhordary commited on
Commit
7119b66
·
verified ·
1 Parent(s): bf69d9b

Create sovereign_bank_benchmark_report.py

Browse files
Files changed (1) hide show
  1. sovereign_bank_benchmark_report.py +248 -0
sovereign_bank_benchmark_report.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sovereign_bank_benchmark_report.py
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from datetime import datetime, timezone
7
+ from typing import Any, Dict, Optional
8
+
9
+ from sovereign_bank_benchmark import run_bank_benchmark
10
+
11
+
12
+ BENCHMARK_OUTPUT_DIR = "sovereign_benchmark_outputs"
13
+
14
+
15
+ def _utc_now() -> str:
16
+ return datetime.now(timezone.utc).isoformat()
17
+
18
+
19
+ def _ensure_dir(path: str) -> None:
20
+ os.makedirs(path, exist_ok=True)
21
+
22
+
23
+ def _safe(v: Any, default: Any = "") -> Any:
24
+ return v if v is not None else default
25
+
26
+
27
+ def _pct(v: Any) -> str:
28
+ try:
29
+ return f"{float(v):.2f}%"
30
+ except Exception:
31
+ return "0.00%"
32
+
33
+
34
+ def _ms(v: Any) -> str:
35
+ try:
36
+ return f"{float(v):.3f} ms"
37
+ except Exception:
38
+ return "0.000 ms"
39
+
40
+
41
+ def _render_summary(report: Dict[str, Any]) -> str:
42
+ summary = report.get("summary", {})
43
+ overall = summary.get("overall_latency", {})
44
+ counts = summary.get("decision_counts", {})
45
+ pcts = summary.get("decision_percentages", {})
46
+ cfg = report.get("config", {})
47
+
48
+ return f"""# Sovereign Bank Runtime Benchmark Report
49
+
50
+ Generated at: {_safe(report.get("generated_at"), _utc_now())}
51
+
52
+ ## 1. Benchmark Identity
53
+ - Benchmark Name: {_safe(report.get("benchmark_name"), "Sovereign Bank Runtime Benchmark")}
54
+ - Case Count: {_safe(cfg.get("case_count"), 0)}
55
+ - Warmup Runs: {_safe(cfg.get("warmup_runs"), 0)}
56
+ - Iterations Per Case: {_safe(cfg.get("iterations_per_case"), 0)}
57
+ - Total Expected Runs: {_safe(cfg.get("total_expected_runs"), 0)}
58
+
59
+ ## 2. Executive Summary
60
+ - Successful Runs: {_safe(summary.get("successful_runs"), 0)}
61
+ - Failed Runs: {_safe(summary.get("failed_runs"), 0)}
62
+ - Overall Min Latency: {_ms(overall.get("min_ms"))}
63
+ - Overall Avg Latency: {_ms(overall.get("avg_ms"))}
64
+ - Overall Median Latency: {_ms(overall.get("median_ms"))}
65
+ - Overall P95 Latency: {_ms(overall.get("p95_ms"))}
66
+ - Overall P99 Latency: {_ms(overall.get("p99_ms"))}
67
+ - Overall Max Latency: {_ms(overall.get("max_ms"))}
68
+ - Overall Standard Deviation: {_ms(overall.get("stdev_ms"))}
69
+
70
+ ## 3. Decision Distribution
71
+ - ALLOW Count: {_safe(counts.get("ALLOW"), 0)} ({_pct(pcts.get("ALLOW", 0))})
72
+ - FREEZE Count: {_safe(counts.get("FREEZE"), 0)} ({_pct(pcts.get("FREEZE", 0))})
73
+ - BLOCK Count: {_safe(counts.get("BLOCK"), 0)} ({_pct(pcts.get("BLOCK", 0))})
74
+ - UNKNOWN Count: {_safe(counts.get("UNKNOWN"), 0)} ({_pct(pcts.get("UNKNOWN", 0))})
75
+ """
76
+
77
+
78
+ def _render_decision_latency(report: Dict[str, Any]) -> str:
79
+ blocks = ["## 4. Latency by Decision"]
80
+ decision_latency = report.get("decision_latency", {})
81
+
82
+ for decision in ["ALLOW", "FREEZE", "BLOCK", "UNKNOWN"]:
83
+ stats = decision_latency.get(decision, {})
84
+ blocks.append(
85
+ f"""
86
+ ### {decision}
87
+ - Count: {_safe(stats.get("count"), 0)}
88
+ - Min: {_ms(stats.get("min_ms"))}
89
+ - Avg: {_ms(stats.get("avg_ms"))}
90
+ - Median: {_ms(stats.get("median_ms"))}
91
+ - P95: {_ms(stats.get("p95_ms"))}
92
+ - P99: {_ms(stats.get("p99_ms"))}
93
+ - Max: {_ms(stats.get("max_ms"))}
94
+ - Stdev: {_ms(stats.get("stdev_ms"))}
95
+ """.rstrip()
96
+ )
97
+
98
+ return "\n\n".join(blocks)
99
+
100
+
101
+ def _render_case_latency(report: Dict[str, Any]) -> str:
102
+ blocks = ["## 5. Latency by Scenario"]
103
+ case_latency = report.get("case_latency", {})
104
+
105
+ for case_name, stats in case_latency.items():
106
+ blocks.append(
107
+ f"""
108
+ ### {case_name}
109
+ - Count: {_safe(stats.get("count"), 0)}
110
+ - Min: {_ms(stats.get("min_ms"))}
111
+ - Avg: {_ms(stats.get("avg_ms"))}
112
+ - Median: {_ms(stats.get("median_ms"))}
113
+ - P95: {_ms(stats.get("p95_ms"))}
114
+ - P99: {_ms(stats.get("p99_ms"))}
115
+ - Max: {_ms(stats.get("max_ms"))}
116
+ - Stdev: {_ms(stats.get("stdev_ms"))}
117
+ """.rstrip()
118
+ )
119
+
120
+ return "\n\n".join(blocks)
121
+
122
+
123
+ def _render_failures(report: Dict[str, Any]) -> str:
124
+ failures = report.get("failures", [])
125
+ lines = ["## 6. Failures"]
126
+
127
+ if not failures:
128
+ lines.append("- No benchmark failures were recorded.")
129
+ return "\n".join(lines)
130
+
131
+ lines.append(f"- Failure Count: {len(failures)}")
132
+ for item in failures[:25]:
133
+ lines.append(
134
+ f"- Case: {item.get('case')} | Iteration: {item.get('iteration')} | Error: {item.get('error')}"
135
+ )
136
+ if len(failures) > 25:
137
+ lines.append(f"- Additional failures omitted: {len(failures) - 25}")
138
+
139
+ return "\n".join(lines)
140
+
141
+
142
+ def _render_samples(report: Dict[str, Any]) -> str:
143
+ sample_outputs = report.get("sample_outputs", {})
144
+ lines = ["## 7. Sample Decision Outputs"]
145
+
146
+ if not sample_outputs:
147
+ lines.append("- No sample outputs available.")
148
+ return "\n".join(lines)
149
+
150
+ for case_name, sample in sample_outputs.items():
151
+ lines.append(f"### {case_name}")
152
+ lines.append(f"- Decision: {_safe(sample.get('decision'), 'UNKNOWN')}")
153
+ lines.append("```json")
154
+ lines.append(json.dumps(sample.get("sample_result", {}), ensure_ascii=False, indent=2))
155
+ lines.append("```")
156
+
157
+ return "\n".join(lines)
158
+
159
+
160
+ def _render_conclusion(report: Dict[str, Any]) -> str:
161
+ summary = report.get("summary", {})
162
+ overall = summary.get("overall_latency", {})
163
+ p95 = float(overall.get("p95_ms", 0.0) or 0.0)
164
+ failures = int(summary.get("failed_runs", 0) or 0)
165
+
166
+ if failures == 0 and p95 <= 50:
167
+ verdict = "Strong benchmark posture for further bank-grade validation."
168
+ elif failures == 0:
169
+ verdict = "Operationally viable, but latency and performance optimization should continue."
170
+ else:
171
+ verdict = "Benchmark results indicate additional hardening and stability work is required before bank deployment."
172
+
173
+ return f"""## 8. Preliminary Technical Verdict
174
+ {verdict}
175
+
176
+ ## 9. Notes
177
+ - This report reflects the current Sovereign bank runtime entrypoint.
178
+ - Results should be interpreted alongside policy coverage, freeze lifecycle, audit-chain integrity, and upcoming cryptographic hardening.
179
+ - This report is suitable as an engineering benchmark artifact, not yet as a final regulatory submission.
180
+ """
181
+
182
+
183
+ def build_benchmark_markdown(report: Dict[str, Any]) -> str:
184
+ parts = [
185
+ _render_summary(report),
186
+ _render_decision_latency(report),
187
+ _render_case_latency(report),
188
+ _render_failures(report),
189
+ _render_samples(report),
190
+ _render_conclusion(report),
191
+ ]
192
+ return "\n\n".join(parts).strip() + "\n"
193
+
194
+
195
+ def save_benchmark_report(
196
+ report: Dict[str, Any],
197
+ output_dir: str = BENCHMARK_OUTPUT_DIR,
198
+ base_name: Optional[str] = None,
199
+ ) -> Dict[str, str]:
200
+ _ensure_dir(output_dir)
201
+
202
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
203
+ base = base_name or f"sovereign_bank_benchmark_{ts}"
204
+
205
+ json_path = os.path.join(output_dir, f"{base}.json")
206
+ md_path = os.path.join(output_dir, f"{base}.md")
207
+
208
+ with open(json_path, "w", encoding="utf-8") as f:
209
+ json.dump(report, f, ensure_ascii=False, indent=2)
210
+
211
+ markdown = build_benchmark_markdown(report)
212
+ with open(md_path, "w", encoding="utf-8") as f:
213
+ f.write(markdown)
214
+
215
+ return {
216
+ "json_report": json_path,
217
+ "markdown_report": md_path,
218
+ }
219
+
220
+
221
+ def generate_bank_benchmark_report(
222
+ warmup_runs: int = 3,
223
+ iterations: int = 20,
224
+ output_dir: str = BENCHMARK_OUTPUT_DIR,
225
+ base_name: Optional[str] = None,
226
+ ) -> Dict[str, Any]:
227
+ report = run_bank_benchmark(
228
+ warmup_runs=warmup_runs,
229
+ iterations=iterations,
230
+ )
231
+ files = save_benchmark_report(
232
+ report=report,
233
+ output_dir=output_dir,
234
+ base_name=base_name,
235
+ )
236
+
237
+ return {
238
+ "ok": True,
239
+ "generated_at": _utc_now(),
240
+ "report": report,
241
+ "files": files,
242
+ }
243
+
244
+
245
+ if __name__ == "__main__":
246
+ out = generate_bank_benchmark_report(warmup_runs=2, iterations=5)
247
+ print(json.dumps(out, indent=2, ensure_ascii=False))
248
+