|
| 1 | +""" |
| 2 | +T5 Service: Node Health Scoring. |
| 3 | +
|
| 4 | +Calculates heuristic health scores for nodes based on error history. |
| 5 | +Currently limited to "Failure Frequency" as we do not track successful executions yet. |
| 6 | +""" |
| 7 | + |
| 8 | +from typing import List, Dict, Any |
| 9 | +from collections import defaultdict |
| 10 | + |
| 11 | +class NodeHealthService: |
| 12 | + """ |
| 13 | + Analyzes error history to determine node health. |
| 14 | + """ |
| 15 | + |
| 16 | + @staticmethod |
| 17 | + def calculate_node_failures(history: List[Dict[str, Any]]) -> List[Dict[str, Any]]: |
| 18 | + """ |
| 19 | + Calculate failure counts per node type. |
| 20 | + |
| 21 | + Args: |
| 22 | + history: List of error history entries. |
| 23 | + |
| 24 | + Returns: |
| 25 | + List of dicts: [{"node_class": str, "count": int, "last_error": str}, ...] |
| 26 | + Sorted by count descending. |
| 27 | + """ |
| 28 | + node_stats = defaultdict(lambda: {"count": 0, "last_error": "", "node_class": ""}) |
| 29 | + |
| 30 | + for entry in history: |
| 31 | + node_info = entry.get("node_info", {}) |
| 32 | + if not node_info: |
| 33 | + # Try to extract from snapshot if available (legacy) |
| 34 | + continue |
| 35 | + |
| 36 | + node_class = node_info.get("node_class") or node_info.get("node_type") |
| 37 | + if not node_class: |
| 38 | + continue |
| 39 | + |
| 40 | + # Key by node class (type) rather than specific node_id instance |
| 41 | + # to capture systematic improvements needed for a node type. |
| 42 | + key = node_class |
| 43 | + |
| 44 | + try: |
| 45 | + weight = int(entry.get("repeat_count", 1) or 1) |
| 46 | + except Exception: |
| 47 | + weight = 1 |
| 48 | + |
| 49 | + node_stats[key]["node_class"] = node_class |
| 50 | + node_stats[key]["count"] += weight |
| 51 | + node_stats[key]["last_error"] = entry.get("error_type") or "Unknown Error" |
| 52 | + |
| 53 | + # Convert to list and sort |
| 54 | + results = list(node_stats.values()) |
| 55 | + results.sort(key=lambda x: x["count"], reverse=True) |
| 56 | + |
| 57 | + return results |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def calculate_health_score(failures: int, total_executions: int = 0) -> float: |
| 61 | + """ |
| 62 | + Calculate a 0.0-1.0 health score. |
| 63 | + If total_executions is 0 (unknown), score is based on raw failure count decay. |
| 64 | + """ |
| 65 | + if total_executions > 0: |
| 66 | + return max(0.0, 1.0 - (failures / total_executions)) |
| 67 | + |
| 68 | + # Heuristic decay: 1 failure = 0.9, 10 failures = 0.5, 100 failures = 0.1 |
| 69 | + # Simple exponential decay for now |
| 70 | + import math |
| 71 | + return float(max(0.0, 1.0 * (0.95 ** failures))) |
0 commit comments