runbooks 0.7.9__py3-none-any.whl → 0.9.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. runbooks/__init__.py +1 -1
  2. runbooks/cfat/README.md +12 -1
  3. runbooks/cfat/__init__.py +1 -1
  4. runbooks/cfat/assessment/compliance.py +4 -1
  5. runbooks/cfat/assessment/runner.py +42 -34
  6. runbooks/cfat/models.py +1 -1
  7. runbooks/cloudops/__init__.py +123 -0
  8. runbooks/cloudops/base.py +385 -0
  9. runbooks/cloudops/cost_optimizer.py +811 -0
  10. runbooks/cloudops/infrastructure_optimizer.py +29 -0
  11. runbooks/cloudops/interfaces.py +828 -0
  12. runbooks/cloudops/lifecycle_manager.py +29 -0
  13. runbooks/cloudops/mcp_cost_validation.py +678 -0
  14. runbooks/cloudops/models.py +251 -0
  15. runbooks/cloudops/monitoring_automation.py +29 -0
  16. runbooks/cloudops/notebook_framework.py +676 -0
  17. runbooks/cloudops/security_enforcer.py +449 -0
  18. runbooks/common/__init__.py +152 -0
  19. runbooks/common/accuracy_validator.py +1039 -0
  20. runbooks/common/context_logger.py +440 -0
  21. runbooks/common/cross_module_integration.py +594 -0
  22. runbooks/common/enhanced_exception_handler.py +1108 -0
  23. runbooks/common/enterprise_audit_integration.py +634 -0
  24. runbooks/common/mcp_cost_explorer_integration.py +900 -0
  25. runbooks/common/mcp_integration.py +548 -0
  26. runbooks/common/performance_monitor.py +387 -0
  27. runbooks/common/profile_utils.py +216 -0
  28. runbooks/common/rich_utils.py +172 -1
  29. runbooks/feedback/user_feedback_collector.py +440 -0
  30. runbooks/finops/README.md +377 -458
  31. runbooks/finops/__init__.py +4 -21
  32. runbooks/finops/account_resolver.py +279 -0
  33. runbooks/finops/accuracy_cross_validator.py +638 -0
  34. runbooks/finops/aws_client.py +721 -36
  35. runbooks/finops/budget_integration.py +313 -0
  36. runbooks/finops/cli.py +59 -5
  37. runbooks/finops/cost_optimizer.py +1340 -0
  38. runbooks/finops/cost_processor.py +211 -37
  39. runbooks/finops/dashboard_router.py +900 -0
  40. runbooks/finops/dashboard_runner.py +990 -232
  41. runbooks/finops/embedded_mcp_validator.py +288 -0
  42. runbooks/finops/enhanced_dashboard_runner.py +8 -7
  43. runbooks/finops/enhanced_progress.py +327 -0
  44. runbooks/finops/enhanced_trend_visualization.py +423 -0
  45. runbooks/finops/finops_dashboard.py +184 -1829
  46. runbooks/finops/helpers.py +509 -196
  47. runbooks/finops/iam_guidance.py +400 -0
  48. runbooks/finops/markdown_exporter.py +466 -0
  49. runbooks/finops/multi_dashboard.py +1502 -0
  50. runbooks/finops/optimizer.py +15 -15
  51. runbooks/finops/profile_processor.py +2 -2
  52. runbooks/finops/runbooks.inventory.organizations_discovery.log +0 -0
  53. runbooks/finops/runbooks.security.report_generator.log +0 -0
  54. runbooks/finops/runbooks.security.run_script.log +0 -0
  55. runbooks/finops/runbooks.security.security_export.log +0 -0
  56. runbooks/finops/schemas.py +589 -0
  57. runbooks/finops/service_mapping.py +195 -0
  58. runbooks/finops/single_dashboard.py +710 -0
  59. runbooks/finops/tests/test_reference_images_validation.py +1 -1
  60. runbooks/inventory/README.md +12 -1
  61. runbooks/inventory/core/collector.py +157 -29
  62. runbooks/inventory/list_ec2_instances.py +9 -6
  63. runbooks/inventory/list_ssm_parameters.py +10 -10
  64. runbooks/inventory/organizations_discovery.py +210 -164
  65. runbooks/inventory/rich_inventory_display.py +74 -107
  66. runbooks/inventory/run_on_multi_accounts.py +13 -13
  67. runbooks/inventory/runbooks.inventory.organizations_discovery.log +0 -0
  68. runbooks/inventory/runbooks.security.security_export.log +0 -0
  69. runbooks/main.py +1371 -240
  70. runbooks/metrics/dora_metrics_engine.py +711 -17
  71. runbooks/monitoring/performance_monitor.py +433 -0
  72. runbooks/operate/README.md +394 -0
  73. runbooks/operate/base.py +215 -47
  74. runbooks/operate/ec2_operations.py +435 -5
  75. runbooks/operate/iam_operations.py +598 -3
  76. runbooks/operate/privatelink_operations.py +1 -1
  77. runbooks/operate/rds_operations.py +508 -0
  78. runbooks/operate/s3_operations.py +508 -0
  79. runbooks/operate/vpc_endpoints.py +1 -1
  80. runbooks/remediation/README.md +489 -13
  81. runbooks/remediation/base.py +5 -3
  82. runbooks/remediation/commons.py +8 -4
  83. runbooks/security/ENTERPRISE_SECURITY_FRAMEWORK.md +506 -0
  84. runbooks/security/README.md +12 -1
  85. runbooks/security/__init__.py +265 -33
  86. runbooks/security/cloudops_automation_security_validator.py +1164 -0
  87. runbooks/security/compliance_automation.py +12 -10
  88. runbooks/security/compliance_automation_engine.py +1021 -0
  89. runbooks/security/enterprise_security_framework.py +930 -0
  90. runbooks/security/enterprise_security_policies.json +293 -0
  91. runbooks/security/executive_security_dashboard.py +1247 -0
  92. runbooks/security/integration_test_enterprise_security.py +879 -0
  93. runbooks/security/module_security_integrator.py +641 -0
  94. runbooks/security/multi_account_security_controls.py +2254 -0
  95. runbooks/security/real_time_security_monitor.py +1196 -0
  96. runbooks/security/report_generator.py +1 -1
  97. runbooks/security/run_script.py +4 -8
  98. runbooks/security/security_baseline_tester.py +39 -52
  99. runbooks/security/security_export.py +99 -120
  100. runbooks/sre/README.md +472 -0
  101. runbooks/sre/__init__.py +33 -0
  102. runbooks/sre/mcp_reliability_engine.py +1049 -0
  103. runbooks/sre/performance_optimization_engine.py +1032 -0
  104. runbooks/sre/production_monitoring_framework.py +584 -0
  105. runbooks/sre/reliability_monitoring_framework.py +1011 -0
  106. runbooks/validation/__init__.py +2 -2
  107. runbooks/validation/benchmark.py +154 -149
  108. runbooks/validation/cli.py +159 -147
  109. runbooks/validation/mcp_validator.py +291 -248
  110. runbooks/vpc/README.md +478 -0
  111. runbooks/vpc/__init__.py +2 -2
  112. runbooks/vpc/manager_interface.py +366 -351
  113. runbooks/vpc/networking_wrapper.py +68 -36
  114. runbooks/vpc/rich_formatters.py +22 -8
  115. runbooks-0.9.1.dist-info/METADATA +308 -0
  116. {runbooks-0.7.9.dist-info → runbooks-0.9.1.dist-info}/RECORD +120 -59
  117. {runbooks-0.7.9.dist-info → runbooks-0.9.1.dist-info}/entry_points.txt +1 -1
  118. runbooks/finops/cross_validation.py +0 -375
  119. runbooks-0.7.9.dist-info/METADATA +0 -636
  120. {runbooks-0.7.9.dist-info → runbooks-0.9.1.dist-info}/WHEEL +0 -0
  121. {runbooks-0.7.9.dist-info → runbooks-0.9.1.dist-info}/licenses/LICENSE +0 -0
  122. {runbooks-0.7.9.dist-info → runbooks-0.9.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,638 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Accuracy Cross-Validator - Real-Time Numerical Verification Engine
4
+ ================================================================
5
+
6
+ BUSINESS CRITICAL: "Are you really 100% sure about ALL of NUMBERS & figures?"
7
+
8
+ This module provides real-time cross-validation of ALL numerical data displayed
9
+ in FinOps dashboards, ensuring 100% accuracy with enterprise-grade validation.
10
+
11
+ Features:
12
+ - Real-time cross-validation between multiple data sources
13
+ - Automated discrepancy detection and alerting
14
+ - 99.99% accuracy validation with <0.01% tolerance
15
+ - Live accuracy scoring and quality gates
16
+ - Complete audit trail for compliance reporting
17
+ - Performance optimized for enterprise scale
18
+ """
19
+
20
+ import asyncio
21
+ import json
22
+ import logging
23
+ import time
24
+ from dataclasses import dataclass, field
25
+ from datetime import datetime, timedelta
26
+ from decimal import ROUND_HALF_UP, Decimal, getcontext
27
+ from enum import Enum
28
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
29
+
30
+ # Set decimal context for financial precision
31
+ getcontext().prec = 28
32
+
33
+ import boto3
34
+ from rich.console import Console
35
+ from rich.panel import Panel
36
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
37
+ from rich.table import Table
38
+
39
+ from ..common.rich_utils import (
40
+ console as rich_console,
41
+ )
42
+ from ..common.rich_utils import (
43
+ format_cost,
44
+ print_error,
45
+ print_info,
46
+ print_success,
47
+ print_warning,
48
+ )
49
+
50
+
51
+ class ValidationStatus(Enum):
52
+ """Validation status enumeration for clear status tracking."""
53
+
54
+ PASSED = "PASSED"
55
+ FAILED = "FAILED"
56
+ WARNING = "WARNING"
57
+ ERROR = "ERROR"
58
+ IN_PROGRESS = "IN_PROGRESS"
59
+
60
+
61
+ class AccuracyLevel(Enum):
62
+ """Accuracy level definitions for enterprise compliance."""
63
+
64
+ ENTERPRISE = 99.99 # 99.99% - Enterprise financial reporting
65
+ BUSINESS = 99.50 # 99.50% - Business intelligence
66
+ OPERATIONAL = 95.00 # 95.00% - Operational monitoring
67
+ DEVELOPMENT = 90.00 # 90.00% - Development/testing
68
+
69
+
70
+ @dataclass
71
+ class ValidationResult:
72
+ """Comprehensive validation result with full audit trail."""
73
+
74
+ description: str
75
+ calculated_value: Union[float, int, str]
76
+ reference_value: Union[float, int, str]
77
+ accuracy_percent: float
78
+ absolute_difference: float
79
+ tolerance_met: bool
80
+ validation_status: ValidationStatus
81
+ source: str
82
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
83
+ metadata: Dict[str, Any] = field(default_factory=dict)
84
+
85
+
86
+ @dataclass
87
+ class CrossValidationReport:
88
+ """Comprehensive cross-validation report for enterprise audit."""
89
+
90
+ total_validations: int
91
+ passed_validations: int
92
+ failed_validations: int
93
+ overall_accuracy: float
94
+ accuracy_level_met: AccuracyLevel
95
+ validation_results: List[ValidationResult]
96
+ execution_time: float
97
+ report_timestamp: str
98
+ compliance_status: Dict[str, Any]
99
+ quality_gates: Dict[str, bool]
100
+
101
+
102
+ class AccuracyCrossValidator:
103
+ """
104
+ Enterprise-grade accuracy cross-validation engine.
105
+
106
+ Provides real-time numerical accuracy verification with comprehensive
107
+ audit trails and quality gates for financial compliance.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ accuracy_level: AccuracyLevel = AccuracyLevel.ENTERPRISE,
113
+ tolerance_percent: float = 0.01,
114
+ console: Optional[Console] = None,
115
+ ):
116
+ """
117
+ Initialize accuracy cross-validator.
118
+
119
+ Args:
120
+ accuracy_level: Required accuracy level (default: ENTERPRISE 99.99%)
121
+ tolerance_percent: Tolerance threshold (default: 0.01%)
122
+ console: Rich console for output (optional)
123
+ """
124
+ self.accuracy_level = accuracy_level
125
+ self.tolerance_percent = tolerance_percent
126
+ self.console = console or rich_console
127
+ self.validation_results: List[ValidationResult] = []
128
+ self.logger = logging.getLogger(__name__)
129
+
130
+ # Performance tracking
131
+ self.validation_start_time = None
132
+ self.validation_counts = {
133
+ ValidationStatus.PASSED: 0,
134
+ ValidationStatus.FAILED: 0,
135
+ ValidationStatus.WARNING: 0,
136
+ ValidationStatus.ERROR: 0,
137
+ }
138
+
139
+ def validate_financial_calculation(
140
+ self, calculated_value: float, reference_value: float, description: str, source: str = "financial_calculation"
141
+ ) -> ValidationResult:
142
+ """
143
+ Validate financial calculation with enterprise precision.
144
+
145
+ Args:
146
+ calculated_value: System calculated value
147
+ reference_value: Reference/expected value
148
+ description: Description of calculation
149
+ source: Source identifier for audit trail
150
+
151
+ Returns:
152
+ Comprehensive validation result
153
+ """
154
+ # Use Decimal for precise financial calculations
155
+ calc_decimal = Decimal(str(calculated_value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
156
+ ref_decimal = Decimal(str(reference_value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
157
+
158
+ # Calculate accuracy metrics
159
+ if ref_decimal != 0:
160
+ accuracy_percent = float((1 - abs(calc_decimal - ref_decimal) / abs(ref_decimal)) * 100)
161
+ else:
162
+ accuracy_percent = 100.0 if calc_decimal == 0 else 0.0
163
+
164
+ absolute_difference = float(abs(calc_decimal - ref_decimal))
165
+
166
+ # Determine validation status
167
+ tolerance_met = (absolute_difference / max(float(abs(ref_decimal)), 1)) * 100 <= self.tolerance_percent
168
+ accuracy_met = accuracy_percent >= self.accuracy_level.value
169
+
170
+ if accuracy_met and tolerance_met:
171
+ validation_status = ValidationStatus.PASSED
172
+ elif accuracy_percent >= AccuracyLevel.BUSINESS.value:
173
+ validation_status = ValidationStatus.WARNING
174
+ else:
175
+ validation_status = ValidationStatus.FAILED
176
+
177
+ # Create validation result
178
+ result = ValidationResult(
179
+ description=description,
180
+ calculated_value=float(calc_decimal),
181
+ reference_value=float(ref_decimal),
182
+ accuracy_percent=accuracy_percent,
183
+ absolute_difference=absolute_difference,
184
+ tolerance_met=tolerance_met,
185
+ validation_status=validation_status,
186
+ source=source,
187
+ metadata={
188
+ "accuracy_level_required": self.accuracy_level.value,
189
+ "tolerance_threshold": self.tolerance_percent,
190
+ "precision_used": "Decimal_2dp",
191
+ },
192
+ )
193
+
194
+ # Track result
195
+ self._track_validation_result(result)
196
+ return result
197
+
198
+ def validate_count_accuracy(
199
+ self, calculated_count: int, reference_count: int, description: str, source: str = "count_validation"
200
+ ) -> ValidationResult:
201
+ """
202
+ Validate count accuracy (must be exact for counts).
203
+
204
+ Args:
205
+ calculated_count: System calculated count
206
+ reference_count: Reference count
207
+ description: Description of count
208
+ source: Source identifier
209
+
210
+ Returns:
211
+ Validation result (exact match required for counts)
212
+ """
213
+ # Counts must be exact integers
214
+ accuracy_percent = 100.0 if calculated_count == reference_count else 0.0
215
+ absolute_difference = abs(calculated_count - reference_count)
216
+
217
+ validation_status = ValidationStatus.PASSED if accuracy_percent == 100.0 else ValidationStatus.FAILED
218
+
219
+ result = ValidationResult(
220
+ description=description,
221
+ calculated_value=calculated_count,
222
+ reference_value=reference_count,
223
+ accuracy_percent=accuracy_percent,
224
+ absolute_difference=absolute_difference,
225
+ tolerance_met=accuracy_percent == 100.0,
226
+ validation_status=validation_status,
227
+ source=source,
228
+ metadata={"validation_type": "exact_count_match", "precision_required": "integer_exact"},
229
+ )
230
+
231
+ self._track_validation_result(result)
232
+ return result
233
+
234
+ def validate_percentage_calculation(
235
+ self,
236
+ calculated_percent: float,
237
+ numerator: float,
238
+ denominator: float,
239
+ description: str,
240
+ source: str = "percentage_calculation",
241
+ ) -> ValidationResult:
242
+ """
243
+ Validate percentage calculation with mathematical verification.
244
+
245
+ Args:
246
+ calculated_percent: System calculated percentage
247
+ numerator: Numerator value
248
+ denominator: Denominator value
249
+ description: Description of percentage
250
+ source: Source identifier
251
+
252
+ Returns:
253
+ Validation result with mathematical verification
254
+ """
255
+ # Calculate expected percentage
256
+ if denominator != 0:
257
+ expected_percent = (numerator / denominator) * 100
258
+ else:
259
+ expected_percent = 0.0
260
+
261
+ return self.validate_financial_calculation(
262
+ calculated_percent, expected_percent, f"Percentage Validation: {description}", f"{source}_percentage"
263
+ )
264
+
265
+ def validate_sum_aggregation(
266
+ self, calculated_sum: float, individual_values: List[float], description: str, source: str = "sum_aggregation"
267
+ ) -> ValidationResult:
268
+ """
269
+ Validate sum aggregation accuracy.
270
+
271
+ Args:
272
+ calculated_sum: System calculated sum
273
+ individual_values: Individual values to sum
274
+ description: Description of aggregation
275
+ source: Source identifier
276
+
277
+ Returns:
278
+ Validation result for aggregation
279
+ """
280
+ # Calculate expected sum with safe Decimal precision
281
+ try:
282
+ # Convert each value safely to Decimal
283
+ decimal_values = []
284
+ for val in individual_values:
285
+ try:
286
+ decimal_val = Decimal(str(val)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
287
+ decimal_values.append(decimal_val)
288
+ except:
289
+ # If individual value fails, use rounded float
290
+ decimal_values.append(Decimal(str(round(float(val), 2))))
291
+
292
+ expected_sum = sum(decimal_values)
293
+ except Exception:
294
+ # Ultimate fallback to float calculation
295
+ expected_sum = Decimal(str(round(sum(individual_values), 2)))
296
+
297
+ return self.validate_financial_calculation(
298
+ calculated_sum, float(expected_sum), f"Sum Aggregation: {description}", f"{source}_aggregation"
299
+ )
300
+
301
+ async def cross_validate_with_aws_api(
302
+ self, runbooks_data: Dict[str, Any], aws_profiles: List[str]
303
+ ) -> List[ValidationResult]:
304
+ """
305
+ Cross-validate runbooks data against AWS API independently.
306
+
307
+ Args:
308
+ runbooks_data: Data from runbooks analysis
309
+ aws_profiles: AWS profiles for independent validation
310
+
311
+ Returns:
312
+ List of cross-validation results
313
+ """
314
+ cross_validation_results = []
315
+
316
+ with Progress(
317
+ SpinnerColumn(),
318
+ TextColumn("[progress.description]{task.description}"),
319
+ BarColumn(),
320
+ TaskProgressColumn(),
321
+ console=self.console,
322
+ ) as progress:
323
+ task = progress.add_task("Cross-validating with AWS APIs...", total=len(aws_profiles))
324
+
325
+ for profile in aws_profiles:
326
+ try:
327
+ # Get independent AWS data
328
+ aws_data = await self._get_independent_aws_data(profile)
329
+
330
+ # Find corresponding runbooks data
331
+ runbooks_profile_data = self._extract_profile_data(runbooks_data, profile)
332
+
333
+ # Validate total costs
334
+ if "total_cost" in runbooks_profile_data and "total_cost" in aws_data:
335
+ cost_validation = self.validate_financial_calculation(
336
+ runbooks_profile_data["total_cost"],
337
+ aws_data["total_cost"],
338
+ f"Total cost cross-validation: {profile[:30]}...",
339
+ "aws_api_cross_validation",
340
+ )
341
+ cross_validation_results.append(cost_validation)
342
+
343
+ # Validate service-level costs
344
+ runbooks_services = runbooks_profile_data.get("services", {})
345
+ aws_services = aws_data.get("services", {})
346
+
347
+ for service in set(runbooks_services.keys()) & set(aws_services.keys()):
348
+ service_validation = self.validate_financial_calculation(
349
+ runbooks_services[service],
350
+ aws_services[service],
351
+ f"Service cost cross-validation: {service}",
352
+ f"aws_api_service_validation_{profile[:20]}",
353
+ )
354
+ cross_validation_results.append(service_validation)
355
+
356
+ progress.advance(task)
357
+
358
+ except Exception as e:
359
+ error_result = ValidationResult(
360
+ description=f"Cross-validation error for {profile[:30]}...",
361
+ calculated_value=0.0,
362
+ reference_value=0.0,
363
+ accuracy_percent=0.0,
364
+ absolute_difference=0.0,
365
+ tolerance_met=False,
366
+ validation_status=ValidationStatus.ERROR,
367
+ source="aws_api_cross_validation_error",
368
+ metadata={"error": str(e)},
369
+ )
370
+ cross_validation_results.append(error_result)
371
+ self._track_validation_result(error_result)
372
+ progress.advance(task)
373
+
374
+ return cross_validation_results
375
+
376
+ async def _get_independent_aws_data(self, profile: str) -> Dict[str, Any]:
377
+ """Get independent cost data from AWS API for cross-validation."""
378
+ try:
379
+ session = boto3.Session(profile_name=profile)
380
+ ce_client = session.client("ce", region_name="us-east-1")
381
+
382
+ # Get current month cost data
383
+ end_date = datetime.now().date()
384
+ start_date = end_date.replace(day=1)
385
+
386
+ response = ce_client.get_cost_and_usage(
387
+ TimePeriod={"Start": start_date.isoformat(), "End": end_date.isoformat()},
388
+ Granularity="MONTHLY",
389
+ Metrics=["BlendedCost"],
390
+ GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
391
+ )
392
+
393
+ # Process response
394
+ total_cost = 0.0
395
+ services = {}
396
+
397
+ if response.get("ResultsByTime"):
398
+ for result in response["ResultsByTime"]:
399
+ for group in result.get("Groups", []):
400
+ service = group.get("Keys", ["Unknown"])[0]
401
+ cost = float(group.get("Metrics", {}).get("BlendedCost", {}).get("Amount", 0))
402
+ services[service] = cost
403
+ total_cost += cost
404
+
405
+ return {
406
+ "total_cost": total_cost,
407
+ "services": services,
408
+ "profile": profile,
409
+ "data_source": "independent_aws_api",
410
+ }
411
+
412
+ except Exception as e:
413
+ return {
414
+ "total_cost": 0.0,
415
+ "services": {},
416
+ "profile": profile,
417
+ "data_source": "error_fallback",
418
+ "error": str(e),
419
+ }
420
+
421
+ def _extract_profile_data(self, runbooks_data: Dict[str, Any], profile: str) -> Dict[str, Any]:
422
+ """Extract data for specific profile from runbooks results."""
423
+ # Adapt based on actual runbooks data structure
424
+ # This is a simplified implementation
425
+ return {
426
+ "total_cost": runbooks_data.get("total_cost", 0.0),
427
+ "services": runbooks_data.get("services", {}),
428
+ "profile": profile,
429
+ }
430
+
431
+ def _track_validation_result(self, result: ValidationResult) -> None:
432
+ """Track validation result for reporting."""
433
+ self.validation_results.append(result)
434
+ self.validation_counts[result.validation_status] += 1
435
+
436
+ def generate_accuracy_report(self) -> CrossValidationReport:
437
+ """
438
+ Generate comprehensive accuracy report for enterprise compliance.
439
+
440
+ Returns:
441
+ Complete cross-validation report with audit trail
442
+ """
443
+ if not self.validation_results:
444
+ return CrossValidationReport(
445
+ total_validations=0,
446
+ passed_validations=0,
447
+ failed_validations=0,
448
+ overall_accuracy=0.0,
449
+ accuracy_level_met=AccuracyLevel.DEVELOPMENT,
450
+ validation_results=[],
451
+ execution_time=0.0,
452
+ report_timestamp=datetime.now().isoformat(),
453
+ compliance_status={"status": "NO_VALIDATIONS"},
454
+ quality_gates={"audit_ready": False},
455
+ )
456
+
457
+ # Calculate metrics
458
+ total_validations = len(self.validation_results)
459
+ passed_validations = self.validation_counts[ValidationStatus.PASSED]
460
+ failed_validations = self.validation_counts[ValidationStatus.FAILED]
461
+
462
+ # Calculate overall accuracy
463
+ valid_results = [r for r in self.validation_results if r.accuracy_percent > 0]
464
+ if valid_results:
465
+ overall_accuracy = sum(r.accuracy_percent for r in valid_results) / len(valid_results)
466
+ else:
467
+ overall_accuracy = 0.0
468
+
469
+ # Determine accuracy level met
470
+ accuracy_level_met = AccuracyLevel.DEVELOPMENT
471
+ if overall_accuracy >= AccuracyLevel.ENTERPRISE.value:
472
+ accuracy_level_met = AccuracyLevel.ENTERPRISE
473
+ elif overall_accuracy >= AccuracyLevel.BUSINESS.value:
474
+ accuracy_level_met = AccuracyLevel.BUSINESS
475
+ elif overall_accuracy >= AccuracyLevel.OPERATIONAL.value:
476
+ accuracy_level_met = AccuracyLevel.OPERATIONAL
477
+
478
+ # Calculate execution time
479
+ execution_time = time.time() - (self.validation_start_time or time.time())
480
+
481
+ # Compliance assessment
482
+ compliance_status = {
483
+ "enterprise_grade": overall_accuracy >= AccuracyLevel.ENTERPRISE.value,
484
+ "audit_ready": overall_accuracy >= AccuracyLevel.ENTERPRISE.value
485
+ and (passed_validations / total_validations) >= 0.95,
486
+ "regulatory_compliant": overall_accuracy >= AccuracyLevel.BUSINESS.value,
487
+ "meets_tolerance": sum(1 for r in self.validation_results if r.tolerance_met) / total_validations >= 0.95,
488
+ }
489
+
490
+ # Quality gates
491
+ quality_gates = {
492
+ "accuracy_threshold_met": overall_accuracy >= self.accuracy_level.value,
493
+ "tolerance_requirements_met": compliance_status["meets_tolerance"],
494
+ "performance_acceptable": execution_time < 30.0, # 30 second performance target
495
+ "audit_ready": compliance_status["audit_ready"],
496
+ }
497
+
498
+ return CrossValidationReport(
499
+ total_validations=total_validations,
500
+ passed_validations=passed_validations,
501
+ failed_validations=failed_validations,
502
+ overall_accuracy=overall_accuracy,
503
+ accuracy_level_met=accuracy_level_met,
504
+ validation_results=self.validation_results,
505
+ execution_time=execution_time,
506
+ report_timestamp=datetime.now().isoformat(),
507
+ compliance_status=compliance_status,
508
+ quality_gates=quality_gates,
509
+ )
510
+
511
+ def display_accuracy_report(self, report: CrossValidationReport) -> None:
512
+ """Display accuracy report with Rich CLI formatting."""
513
+ # Create summary table
514
+ summary_table = Table(title="📊 Numerical Accuracy Validation Report")
515
+ summary_table.add_column("Metric", style="cyan")
516
+ summary_table.add_column("Value", style="green")
517
+ summary_table.add_column("Status", style="bold")
518
+
519
+ # Add summary rows
520
+ summary_table.add_row("Total Validations", str(report.total_validations), "📋")
521
+ summary_table.add_row("Passed Validations", str(report.passed_validations), "✅")
522
+ summary_table.add_row(
523
+ "Failed Validations", str(report.failed_validations), "❌" if report.failed_validations > 0 else "✅"
524
+ )
525
+ summary_table.add_row(
526
+ "Overall Accuracy",
527
+ f"{report.overall_accuracy:.2f}%",
528
+ "✅" if report.overall_accuracy >= self.accuracy_level.value else "⚠️",
529
+ )
530
+ summary_table.add_row(
531
+ "Accuracy Level",
532
+ report.accuracy_level_met.name,
533
+ "🏆" if report.accuracy_level_met == AccuracyLevel.ENTERPRISE else "📊",
534
+ )
535
+ summary_table.add_row(
536
+ "Execution Time", f"{report.execution_time:.2f}s", "⚡" if report.execution_time < 30 else "⏰"
537
+ )
538
+
539
+ self.console.print(summary_table)
540
+
541
+ # Compliance status
542
+ if report.compliance_status["audit_ready"]:
543
+ print_success("✅ System meets enterprise audit requirements")
544
+ elif report.compliance_status["enterprise_grade"]:
545
+ print_warning("⚠️ Enterprise accuracy achieved, but validation coverage needs improvement")
546
+ else:
547
+ print_error("❌ System does not meet enterprise accuracy requirements")
548
+
549
+ # Quality gates summary
550
+ gates_passed = sum(1 for gate_met in report.quality_gates.values() if gate_met)
551
+ gates_total = len(report.quality_gates)
552
+
553
+ if gates_passed == gates_total:
554
+ print_success(f"✅ All quality gates passed ({gates_passed}/{gates_total})")
555
+ else:
556
+ print_warning(f"⚠️ Quality gates: {gates_passed}/{gates_total} passed")
557
+
558
+ def export_audit_report(self, report: CrossValidationReport, file_path: str) -> None:
559
+ """Export comprehensive audit report for compliance review."""
560
+ audit_data = {
561
+ "report_metadata": {
562
+ "report_type": "numerical_accuracy_cross_validation",
563
+ "accuracy_level_required": self.accuracy_level.name,
564
+ "tolerance_threshold": self.tolerance_percent,
565
+ "report_timestamp": report.report_timestamp,
566
+ "execution_time": report.execution_time,
567
+ },
568
+ "summary_metrics": {
569
+ "total_validations": report.total_validations,
570
+ "passed_validations": report.passed_validations,
571
+ "failed_validations": report.failed_validations,
572
+ "overall_accuracy": report.overall_accuracy,
573
+ "accuracy_level_achieved": report.accuracy_level_met.name,
574
+ },
575
+ "compliance_assessment": report.compliance_status,
576
+ "quality_gates": report.quality_gates,
577
+ "detailed_validation_results": [
578
+ {
579
+ "description": r.description,
580
+ "calculated_value": r.calculated_value,
581
+ "reference_value": r.reference_value,
582
+ "accuracy_percent": r.accuracy_percent,
583
+ "absolute_difference": r.absolute_difference,
584
+ "tolerance_met": r.tolerance_met,
585
+ "validation_status": r.validation_status.value,
586
+ "source": r.source,
587
+ "timestamp": r.timestamp,
588
+ "metadata": r.metadata,
589
+ }
590
+ for r in report.validation_results
591
+ ],
592
+ }
593
+
594
+ with open(file_path, "w") as f:
595
+ json.dump(audit_data, f, indent=2, default=str)
596
+
597
+ def start_validation_session(self) -> None:
598
+ """Start validation session timing."""
599
+ self.validation_start_time = time.time()
600
+ self.validation_results.clear()
601
+ self.validation_counts = {status: 0 for status in ValidationStatus}
602
+
603
+
604
+ # Convenience functions for integration
605
+ def create_accuracy_validator(
606
+ accuracy_level: AccuracyLevel = AccuracyLevel.ENTERPRISE, tolerance_percent: float = 0.01
607
+ ) -> AccuracyCrossValidator:
608
+ """Factory function to create accuracy cross-validator."""
609
+ return AccuracyCrossValidator(accuracy_level=accuracy_level, tolerance_percent=tolerance_percent)
610
+
611
+
612
+ async def validate_finops_data_accuracy(
613
+ runbooks_data: Dict[str, Any], aws_profiles: List[str], accuracy_level: AccuracyLevel = AccuracyLevel.ENTERPRISE
614
+ ) -> CrossValidationReport:
615
+ """
616
+ Comprehensive FinOps data accuracy validation.
617
+
618
+ Args:
619
+ runbooks_data: Data from runbooks FinOps analysis
620
+ aws_profiles: AWS profiles for cross-validation
621
+ accuracy_level: Required accuracy level
622
+
623
+ Returns:
624
+ Complete validation report
625
+ """
626
+ validator = create_accuracy_validator(accuracy_level=accuracy_level)
627
+ validator.start_validation_session()
628
+
629
+ # Perform cross-validation with AWS APIs
630
+ cross_validation_results = await validator.cross_validate_with_aws_api(runbooks_data, aws_profiles)
631
+
632
+ # Generate comprehensive report
633
+ report = validator.generate_accuracy_report()
634
+
635
+ # Display results
636
+ validator.display_accuracy_report(report)
637
+
638
+ return report