Spaces:
Configuration error
Configuration error
feat(diagnostics): Add code bug exposure system v0.6.0
Browse filesNEW: cascade.diagnostics module
- BugDetector: Static analysis for Python code
- CodeTracer: Runtime execution tracing with causation chains
- ExecutionMonitor: Live monitoring with anomaly detection
- DiagnosticEngine: Unified reporting with markdown output
Bug patterns detected:
- Division by zero, null pointer access, infinite loops (Critical)
- Bare except, resource leaks, race conditions (High)
- Unused variables, dead code, type mismatches (Medium)
- Style issues, naming conventions (Low)
Usage:
from cascade.diagnostics import diagnose, BugDetector
report = diagnose('path/to/code.py')
issues = BugDetector().scan_directory('./project')
Also: Updated README with diagnostics docs, keywords in pyproject.toml
Files changed (9)
- README.md+40-1
- cascade/__init__.py+6-1
- cascade/diagnostics/__init__.pyAdded+73
- cascade/diagnostics/bug_detector.pyAdded+590
- cascade/diagnostics/code_tracer.pyAdded+512
- cascade/diagnostics/demo.pyAdded+299
- cascade/diagnostics/execution_monitor.pyAdded+473
- cascade/diagnostics/report.pyAdded+432
- pyproject.toml+3-2
12345659 unmodified lines666768697071# cascade-lattice**Universal AI provenance + inference intervention. See what AI sees. Choose what AI chooses.**[](https://pypi.org/project/cascade-lattice/)[](https://pypi.org/project/cascade-lattice/)59 unmodified linesaction = resolution.action```---## Quick Start12345659 unmodified lines66676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# cascade-lattice**Universal AI provenance + inference intervention + code diagnostics. See what AI sees. Choose what AI chooses. Find bugs before they find you.**[](https://pypi.org/project/cascade-lattice/)[](https://pypi.org/project/cascade-lattice/)59 unmodified linesaction = resolution.action```### 3. DIAGNOSE - Find bugs before they find you```pythonfrom cascade.diagnostics import diagnose, BugDetector# Quick one-liner analysisreport = diagnose("path/to/your/code.py")print(report) # Markdown-formatted bug report# Deep scan a whole projectdetector = BugDetector()issues = detector.scan_directory("./my_project")for issue in issues:print(f"[{issue.severity}] {issue.file}:{issue.line}")print(f" {issue.message}")print(f" Pattern: {issue.pattern.name}")```**What it catches:**- 🔴 **Critical**: Division by zero, null pointer access, infinite loops- 🟠 **High**: Bare except clauses, resource leaks, race conditions- 🟡 **Medium**: Unused variables, dead code, type mismatches- 🔵 **Low**: Style issues, naming conventions, complexity warnings**Runtime tracing:**```pythonfrom cascade.diagnostics import CodeTracertracer = CodeTracer()@tracer.tracedef my_function(x):return x / (x - 1) # Potential div by zero when x=1# After execution, trace root causestracer.find_root_causes("error_event_id")```---## Quick Start
33 unmodified lines34353637383940201 unmodified lines24224324424524624738 unmodified lines28628728828929033 unmodified lines>>> monitor.trace_forwards("learning_rate_spike")"""__version__ = "0.5.8"__author__ = "Cascade Team"__license__ = "MIT"201 unmodified linesArcadeFeedback,)__all__ = [# SDK - Primary Interface38 unmodified lines"HoldSession","ArcadeFeedback","hold_module","__version__",]33 unmodified lines34353637383940201 unmodified lines24224324424524624724824925038 unmodified lines28929029129229329429533 unmodified lines>>> monitor.trace_forwards("learning_rate_spike")"""__version__ = "0.6.0"__author__ = "Cascade Team"__license__ = "MIT"201 unmodified linesArcadeFeedback,)# DIAGNOSTICS - Code Bug Exposure Systemfrom cascade import diagnostics__all__ = [# SDK - Primary Interface38 unmodified lines"HoldSession","ArcadeFeedback","hold_module",# Diagnostics - Code Bug Exposure"diagnostics","__version__",]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""CASCADE DIAGNOSTICS - Code Bug Exposure System
A novel application of cascade-lattice: instead of tracing AI inference,we trace CODE EXECUTION to expose bugs - known and unknown.
Core Insight:- cascade-lattice traces causation chains (what caused what)- Forensics module extracts artifacts (evidence of processing)- System module ingests and analyzes repositories- Monitor adapts to ANY signal format (symbiotic)
For DEBUGGING, we repurpose these:- Events = Code execution points, function calls, variable states- CausationLinks = Control flow, data dependencies- Artifacts = Bug signatures, anomaly patterns- GhostLog = Inferred sequence of execution failures- Tracer = Backtrack from crash/bug to root cause
This creates a "debugger on steroids" that:1. OBSERVES code execution at any granularity2. TRACES causation chains to find root causes3. EXPOSES hidden bugs through pattern recognition4. PREDICTS cascading failures before they complete
Usage: from cascade.diagnostics import diagnose, CodeTracer, BugDetector # Quick analysis of a file report = diagnose("path/to/file.py") print(engine.to_markdown(report)) # Trace function execution tracer = CodeTracer() @tracer.trace def my_function(x): return x * 2 # After execution, find root causes tracer.find_root_causes(error_event_id) # Static bug detection detector = BugDetector() issues = detector.scan_directory("./my_project")"""
from cascade.diagnostics.code_tracer import CodeTracer, CodeEvent, BugSignaturefrom cascade.diagnostics.bug_detector import BugDetector, BugPattern, DetectedIssuefrom cascade.diagnostics.execution_monitor import ExecutionMonitor, ExecutionFrame, Anomaly, monitorfrom cascade.diagnostics.report import DiagnosticReport, DiagnosticFinding, DiagnosticEngine, diagnose
__all__ = [ # Main classes "CodeTracer", "BugDetector", "ExecutionMonitor", "DiagnosticReport", "DiagnosticEngine", # Data classes "CodeEvent", "BugSignature", "BugPattern", "DetectedIssue", "ExecutionFrame", "Anomaly", "DiagnosticFinding", # Convenience "diagnose", "monitor",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590"""CASCADE Bug Detector - Automatic bug detection using pattern matching.
Uses cascade-lattice's forensic capabilities:- GhostLog for inferring missing execution (what *should* have run)- Artifact patterns for detecting anomalies- SymbioticAdapter for interpreting signals"""
import timeimport hashlibfrom typing import Any, Dict, List, Optional, Set, Callable, Tuplefrom dataclasses import dataclass, fieldfrom pathlib import Pathimport astimport re
from cascade.core.adapter import SymbioticAdapterfrom cascade.forensics.artifacts import ArtifactDetector, TimestampArtifacts
@dataclassclass BugPattern: """A detectable bug pattern.""" name: str description: str severity: str # "critical", "error", "warning", "info" detector: Callable[[str, ast.AST], List[Dict[str, Any]]] category: str = "general" @dataclass class DetectedIssue: """A detected code issue.""" issue_id: str pattern_name: str severity: str file_path: str line_number: int column: int code_snippet: str message: str suggestion: Optional[str] = None confidence: float = 1.0 def to_dict(self) -> Dict[str, Any]: return { "id": self.issue_id, "pattern": self.pattern_name, "severity": self.severity, "location": { "file": self.file_path, "line": self.line_number, "column": self.column, }, "snippet": self.code_snippet, "message": self.message, "suggestion": self.suggestion, "confidence": self.confidence, }
class BugDetector: """ Static analysis bug detector using AST patterns. Usage: detector = BugDetector() issues = detector.scan_file("path/to/file.py") issues = detector.scan_directory("path/to/project") """ def __init__(self): self.patterns: List[BugPattern] = [] self._detected_issues: List[DetectedIssue] = [] self._scanned_files: Set[str] = set() # For signal interpretation self.adapter = SymbioticAdapter() # Register built-in patterns self._register_builtin_patterns() def _register_builtin_patterns(self): """Register built-in bug detection patterns.""" patterns = [ # Null checks BugPattern( name="potential_none_access", description="Accessing attribute on potentially None value", severity="warning", detector=self._detect_none_access, category="null_safety", ), # Exception handling BugPattern( name="bare_except", description="Bare except clause catches all exceptions", severity="warning", detector=self._detect_bare_except, category="exception_handling", ), BugPattern( name="empty_except", description="Empty except block silently swallows exceptions", severity="error", detector=self._detect_empty_except, category="exception_handling", ), # Resource management BugPattern( name="unclosed_resource", description="File/resource opened but not closed", severity="warning", detector=self._detect_unclosed_resource, category="resource_management", ), # Common mistakes BugPattern( name="mutable_default_arg", description="Mutable default argument in function", severity="warning", detector=self._detect_mutable_default, category="common_mistakes", ), BugPattern( name="comparison_to_none", description="Using == instead of 'is' for None comparison", severity="info", detector=self._detect_none_comparison, category="common_mistakes", ), BugPattern( name="unreachable_code", description="Code that can never be executed", severity="warning", detector=self._detect_unreachable_code, category="common_mistakes", ), # Security BugPattern( name="hardcoded_secret", description="Potential hardcoded secret or password", severity="error", detector=self._detect_hardcoded_secret, category="security", ), BugPattern( name="sql_injection_risk", description="Potential SQL injection vulnerability", severity="critical", detector=self._detect_sql_injection, category="security", ), # Performance BugPattern( name="loop_invariant", description="Computation inside loop that could be moved outside", severity="info", detector=self._detect_loop_invariant, category="performance", ), ] self.patterns.extend(patterns) def register_pattern(self, pattern: BugPattern): """Register a custom bug pattern.""" self.patterns.append(pattern) def scan_file(self, file_path: str) -> List[DetectedIssue]: """Scan a Python file for bugs.""" issues = [] try: with open(file_path, 'r', encoding='utf-8') as f: source = f.read() except Exception as e: return [DetectedIssue( issue_id=self._generate_id(file_path, 0, "read_error"), pattern_name="file_read_error", severity="error", file_path=file_path, line_number=0, column=0, code_snippet="", message=f"Could not read file: {e}", )] try: tree = ast.parse(source) except SyntaxError as e: return [DetectedIssue( issue_id=self._generate_id(file_path, e.lineno or 0, "syntax_error"), pattern_name="syntax_error", severity="critical", file_path=file_path, line_number=e.lineno or 0, column=e.offset or 0, code_snippet=e.text or "", message=f"Syntax error: {e.msg}", )] # Run all patterns lines = source.splitlines() for pattern in self.patterns: try: matches = pattern.detector(source, tree) for match in matches: line_num = match.get("line", 0) snippet = lines[line_num - 1] if 0 < line_num <= len(lines) else "" issues.append(DetectedIssue( issue_id=self._generate_id(file_path, line_num, pattern.name), pattern_name=pattern.name, severity=pattern.severity, file_path=file_path, line_number=line_num, column=match.get("column", 0), code_snippet=snippet.strip(), message=match.get("message", pattern.description), suggestion=match.get("suggestion"), confidence=match.get("confidence", 1.0), )) except Exception as e: print(f"[DIAG] Pattern {pattern.name} failed on {file_path}: {e}") self._scanned_files.add(file_path) self._detected_issues.extend(issues) return issues def scan_directory(self, dir_path: str, recursive: bool = True) -> List[DetectedIssue]: """Scan a directory for Python files and detect bugs.""" path = Path(dir_path) issues = [] pattern = "**/*.py" if recursive else "*.py" for py_file in path.glob(pattern): # Skip __pycache__ if "__pycache__" in str(py_file): continue issues.extend(self.scan_file(str(py_file))) return issues def _generate_id(self, file_path: str, line: int, pattern: str) -> str: """Generate a unique issue ID.""" content = f"{file_path}:{line}:{pattern}" return hashlib.sha256(content.encode()).hexdigest()[:16] # ========================================================================= # PATTERN DETECTORS # ========================================================================= def _detect_none_access(self, source: str, tree: ast.AST) -> List[Dict]: """Detect potential None access.""" matches = [] class Visitor(ast.NodeVisitor): def visit_Attribute(self, node): # Look for patterns like: x.y where x might be None # This is heuristic - check if there's no None check before if isinstance(node.value, ast.Name): # Simple heuristic: flag if variable name suggests nullable name = node.value.id if any(word in name.lower() for word in ["result", "maybe", "optional", "response"]): matches.append({ "line": node.lineno, "column": node.col_offset, "message": f"'{name}' may be None - consider adding a null check", "confidence": 0.6, }) self.generic_visit(node) Visitor().visit(tree) return matches def _detect_bare_except(self, source: str, tree: ast.AST) -> List[Dict]: """Detect bare except clauses.""" matches = [] class Visitor(ast.NodeVisitor): def visit_ExceptHandler(self, node): if node.type is None: matches.append({ "line": node.lineno, "column": node.col_offset, "message": "Bare 'except:' catches all exceptions including KeyboardInterrupt", "suggestion": "Use 'except Exception:' instead", }) self.generic_visit(node) Visitor().visit(tree) return matches def _detect_empty_except(self, source: str, tree: ast.AST) -> List[Dict]: """Detect empty except blocks.""" matches = [] lines = source.splitlines() class Visitor(ast.NodeVisitor): def visit_ExceptHandler(self, node): # Check if body is just 'pass' or empty if len(node.body) == 1: stmt = node.body[0] if isinstance(stmt, ast.Pass): # Check if there's a comment explaining the pass line_idx = stmt.lineno - 1 if line_idx < len(lines): line = lines[line_idx] if '#' in line: # Has a comment - don't flag as issue self.generic_visit(node) return matches.append({ "line": node.lineno, "column": node.col_offset, "message": "Empty except block silently ignores exception", "suggestion": "At minimum, log the exception", }) self.generic_visit(node) Visitor().visit(tree) return matches def _detect_unclosed_resource(self, source: str, tree: ast.AST) -> List[Dict]: """Detect files opened without context manager.""" matches = [] class Visitor(ast.NodeVisitor): def __init__(self): self.in_with = False def visit_With(self, node): old = self.in_with self.in_with = True self.generic_visit(node) self.in_with = old def visit_Call(self, node): if isinstance(node.func, ast.Name) and node.func.id == 'open': if not self.in_with: matches.append({ "line": node.lineno, "column": node.col_offset, "message": "File opened without 'with' context manager", "suggestion": "Use 'with open(...) as f:' to ensure file is closed", }) self.generic_visit(node) Visitor().visit(tree) return matches def _detect_mutable_default(self, source: str, tree: ast.AST) -> List[Dict]: """Detect mutable default arguments.""" matches = [] class Visitor(ast.NodeVisitor): def visit_FunctionDef(self, node): for default in node.args.defaults + node.args.kw_defaults: if default and isinstance(default, (ast.List, ast.Dict, ast.Set)): matches.append({ "line": node.lineno, "column": node.col_offset, "message": f"Mutable default argument in function '{node.name}'", "suggestion": "Use None as default and create mutable object inside function", }) break self.generic_visit(node) def visit_AsyncFunctionDef(self, node): self.visit_FunctionDef(node) Visitor().visit(tree) return matches def _detect_none_comparison(self, source: str, tree: ast.AST) -> List[Dict]: """Detect == None instead of 'is None'.""" matches = [] class Visitor(ast.NodeVisitor): def visit_Compare(self, node): for i, (op, comparator) in enumerate(zip(node.ops, node.comparators)): if isinstance(op, (ast.Eq, ast.NotEq)): if isinstance(comparator, ast.Constant) and comparator.value is None: matches.append({ "line": node.lineno, "column": node.col_offset, "message": "Use 'is None' instead of '== None'", "suggestion": "Replace with 'is None' or 'is not None'", }) self.generic_visit(node) Visitor().visit(tree) return matches def _detect_unreachable_code(self, source: str, tree: ast.AST) -> List[Dict]: """Detect code after return/raise/break/continue.""" matches = [] class Visitor(ast.NodeVisitor): def check_body(self, body): for i, stmt in enumerate(body): if isinstance(stmt, (ast.Return, ast.Raise, ast.Break, ast.Continue)): # Check if there's code after this if i + 1 < len(body): next_stmt = body[i + 1] matches.append({ "line": next_stmt.lineno, "column": next_stmt.col_offset, "message": "Unreachable code after return/raise/break/continue", }) self.visit(stmt) def visit_FunctionDef(self, node): self.check_body(node.body) def visit_AsyncFunctionDef(self, node): self.check_body(node.body) def visit_If(self, node): self.check_body(node.body) self.check_body(node.orelse) def visit_For(self, node): self.check_body(node.body) def visit_While(self, node): self.check_body(node.body) Visitor().visit(tree) return matches def _detect_hardcoded_secret(self, source: str, tree: ast.AST) -> List[Dict]: """Detect potential hardcoded secrets.""" matches = [] # Pattern for secret-like variable names secret_patterns = re.compile( r'\b(password|passwd|pwd|secret|api_key|apikey|token|auth|credential)\s*=\s*["\'][^"\']+["\']', re.IGNORECASE ) for i, line in enumerate(source.splitlines(), 1): if secret_patterns.search(line): matches.append({ "line": i, "column": 0, "message": "Potential hardcoded secret detected", "suggestion": "Use environment variables or a secrets manager", }) return matches def _detect_sql_injection(self, source: str, tree: ast.AST) -> List[Dict]: """Detect potential SQL injection vulnerabilities.""" matches = [] class Visitor(ast.NodeVisitor): def visit_Call(self, node): # Look for .execute() calls with string formatting if isinstance(node.func, ast.Attribute) and node.func.attr == 'execute': for arg in node.args: if isinstance(arg, ast.BinOp) and isinstance(arg.op, ast.Mod): matches.append({ "line": node.lineno, "column": node.col_offset, "message": "Potential SQL injection - using string formatting in query", "suggestion": "Use parameterized queries instead", }) elif isinstance(arg, ast.JoinedStr): # f-string matches.append({ "line": node.lineno, "column": node.col_offset, "message": "Potential SQL injection - using f-string in query", "suggestion": "Use parameterized queries instead", }) self.generic_visit(node) Visitor().visit(tree) return matches def _detect_loop_invariant(self, source: str, tree: ast.AST) -> List[Dict]: """Detect computations that could be moved outside loops.""" matches = [] class Visitor(ast.NodeVisitor): def visit_For(self, node): # Get loop variable name if isinstance(node.target, ast.Name): loop_var = node.target.id # Look for calls that don't use the loop variable for stmt in node.body: if isinstance(stmt, ast.Assign): for target in stmt.targets: if isinstance(target, ast.Name): # Check if value doesn't depend on loop var value_vars = self._get_names(stmt.value) if loop_var not in value_vars and self._is_expensive(stmt.value): matches.append({ "line": stmt.lineno, "column": stmt.col_offset, "message": "Computation inside loop may be loop-invariant", "suggestion": "Consider moving this outside the loop", "confidence": 0.5, }) self.generic_visit(node) def _get_names(self, node) -> Set[str]: names = set() for child in ast.walk(node): if isinstance(child, ast.Name): names.add(child.id) return names def _is_expensive(self, node) -> bool: # Heuristic: calls are potentially expensive for child in ast.walk(node): if isinstance(child, ast.Call): return True return False Visitor().visit(tree) return matches # ========================================================================= # REPORTING # ========================================================================= def get_summary(self) -> Dict[str, Any]: """Get detection summary.""" by_severity = {} by_category = {} for issue in self._detected_issues: by_severity[issue.severity] = by_severity.get(issue.severity, 0) + 1 pattern = next((p for p in self.patterns if p.name == issue.pattern_name), None) if pattern: by_category[pattern.category] = by_category.get(pattern.category, 0) + 1 return { "files_scanned": len(self._scanned_files), "total_issues": len(self._detected_issues), "by_severity": by_severity, "by_category": by_category, } def get_report(self) -> str: """Generate a human-readable report.""" lines = [ "BUG DETECTION REPORT", "=" * 60, f"Files scanned: {len(self._scanned_files)}", f"Issues found: {len(self._detected_issues)}", "", ] # Group by severity by_severity: Dict[str, List[DetectedIssue]] = {} for issue in self._detected_issues: if issue.severity not in by_severity: by_severity[issue.severity] = [] by_severity[issue.severity].append(issue) severity_order = ["critical", "error", "warning", "info"] severity_icons = {"critical": "🔴", "error": "❌", "warning": "⚠️", "info": "ℹ️"} for severity in severity_order: if severity in by_severity: issues = by_severity[severity] icon = severity_icons.get(severity, "•") lines.append(f"\n{icon} {severity.upper()} ({len(issues)})") lines.append("-" * 40) for issue in issues: lines.append(f" {issue.file_path}:{issue.line_number}") lines.append(f" {issue.message}") if issue.suggestion: lines.append(f" 💡 {issue.suggestion}") lines.append("") return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512"""CASCADE Code Tracer - Trace execution through code to find bugs.
Repurposes cascade-lattice's causation graph for code execution:- Each function call = Event- Each return/exception = Event - Control flow = CausationLinks- Data flow = CausationLinks with different type
Enables:- "What called this function?" (trace_backwards)- "What did this function call?" (trace_forwards)- "What was the root cause of this crash?" (find_root_causes)- "What will this bug affect?" (analyze_impact)"""
import sysimport timeimport hashlibimport functoolsimport tracebackimport threadingfrom typing import Any, Dict, List, Optional, Callable, Setfrom dataclasses import dataclass, fieldfrom pathlib import Path
from cascade.core.event import Event, CausationLinkfrom cascade.core.graph import CausationGraphfrom cascade.analysis.tracer import Tracer, RootCauseAnalysis, ImpactAnalysis
@dataclassclass CodeEvent(Event): """ An event in code execution - extends base Event with code-specific data. """ # Code location file_path: str = "" line_number: int = 0 function_name: str = "" class_name: Optional[str] = None module_name: str = "" # Execution context call_stack_depth: int = 0 thread_id: int = 0 # Data snapshot args: Dict[str, Any] = field(default_factory=dict) kwargs: Dict[str, Any] = field(default_factory=dict) return_value: Optional[Any] = None exception: Optional[str] = None # Timing duration_ms: float = 0.0
@dataclassclass BugSignature: """ A detected bug signature - pattern that indicates a problem. """ bug_type: str # "null_reference", "type_mismatch", "infinite_loop", etc. severity: str # "critical", "error", "warning", "info" evidence: List[str] affected_events: List[str] # Event IDs root_cause_event: Optional[str] = None confidence: float = 0.0 def to_dict(self) -> Dict[str, Any]: return { "bug_type": self.bug_type, "severity": self.severity, "evidence": self.evidence, "affected_events": self.affected_events, "root_cause_event": self.root_cause_event, "confidence": self.confidence, }
class CodeTracer: """ Trace code execution using cascade-lattice causation graph. Usage: tracer = CodeTracer() @tracer.trace def my_function(x, y): return x + y # After execution: tracer.find_root_causes(error_event_id) tracer.analyze_impact(function_event_id) tracer.detect_bugs() """ def __init__(self, name: str = "code_tracer"): self.name = name self.graph = CausationGraph() self.tracer = Tracer(self.graph) # Execution tracking self._call_stack: List[str] = [] # Stack of event IDs self._current_depth = 0 self._lock = threading.RLock() # Bug detection patterns self._bug_patterns: List[Callable] = [] self._detected_bugs: List[BugSignature] = [] # Statistics self._event_count = 0 self._error_count = 0 # Register built-in bug detectors self._register_builtin_detectors() def _register_builtin_detectors(self): """Register built-in bug detection patterns.""" self._bug_patterns.extend([ self._detect_null_reference, self._detect_type_errors, self._detect_recursion_depth, self._detect_slow_functions, self._detect_exception_patterns, ]) def trace(self, func: Callable = None, *, capture_args: bool = True): """ Decorator to trace function execution. Usage: @tracer.trace def my_function(x, y): return x + y # Or with options: @tracer.trace(capture_args=False) def sensitive_function(password): ... """ def decorator(fn: Callable) -> Callable: @functools.wraps(fn) def wrapper(*args, **kwargs): return self._traced_call(fn, args, kwargs, capture_args) return wrapper if func is not None: # Called as @tracer.trace without parentheses return decorator(func) return decorator def _traced_call(self, func: Callable, args: tuple, kwargs: dict, capture_args: bool) -> Any: """Execute a traced function call.""" # Create entry event entry_event = self._create_entry_event(func, args, kwargs, capture_args) self.graph.add_event(entry_event) # Link to caller with self._lock: if self._call_stack: caller_id = self._call_stack[-1] link = CausationLink( from_event=caller_id, to_event=entry_event.event_id, causation_type="call", strength=1.0, explanation=f"{func.__name__} called" ) self.graph.add_link(link) self._call_stack.append(entry_event.event_id) self._current_depth += 1 start_time = time.perf_counter() exception_info = None return_value = None try: return_value = func(*args, **kwargs) return return_value except Exception as e: exception_info = str(e) # Re-raise after recording raise finally: duration = (time.perf_counter() - start_time) * 1000 # Create exit event exit_event = self._create_exit_event( func, entry_event, return_value, exception_info, duration ) self.graph.add_event(exit_event) # Link entry -> exit link = CausationLink( from_event=entry_event.event_id, to_event=exit_event.event_id, causation_type="return" if not exception_info else "exception", strength=1.0, explanation=f"{func.__name__} {'returned' if not exception_info else 'raised ' + exception_info}" ) self.graph.add_link(link) with self._lock: self._call_stack.pop() self._current_depth -= 1 if exception_info: self._error_count += 1 def _create_entry_event(self, func: Callable, args: tuple, kwargs: dict, capture_args: bool) -> CodeEvent: """Create an event for function entry.""" # Get source location try: file_path = func.__code__.co_filename line_number = func.__code__.co_firstlineno except AttributeError: file_path = "unknown" line_number = 0 # Get function info module_name = func.__module__ or "" class_name = None if hasattr(func, '__qualname__') and '.' in func.__qualname__: class_name = func.__qualname__.rsplit('.', 1)[0] # Capture arguments (sanitized) captured_args = {} captured_kwargs = {} if capture_args: try: # Get parameter names import inspect sig = inspect.signature(func) params = list(sig.parameters.keys()) for i, arg in enumerate(args): key = params[i] if i < len(params) else f"arg_{i}" captured_args[key] = self._sanitize_value(arg) for k, v in kwargs.items(): captured_kwargs[k] = self._sanitize_value(v) except Exception: pass # Can't capture args - non-critical self._event_count += 1 return CodeEvent( timestamp=time.time(), component=module_name, event_type="function_entry", data={ "function": func.__name__, "args_count": len(args), "kwargs_count": len(kwargs), }, file_path=file_path, line_number=line_number, function_name=func.__name__, class_name=class_name, module_name=module_name, call_stack_depth=self._current_depth, thread_id=threading.current_thread().ident, args=captured_args, kwargs=captured_kwargs, ) def _create_exit_event(self, func: Callable, entry: CodeEvent, return_value: Any, exception: Optional[str], duration_ms: float) -> CodeEvent: """Create an event for function exit.""" event_type = "function_return" if not exception else "function_exception" return CodeEvent( timestamp=time.time(), component=entry.module_name, event_type=event_type, data={ "function": func.__name__, "duration_ms": duration_ms, "exception": exception, "has_return": return_value is not None, }, file_path=entry.file_path, line_number=entry.line_number, function_name=func.__name__, class_name=entry.class_name, module_name=entry.module_name, call_stack_depth=entry.call_stack_depth, thread_id=entry.thread_id, return_value=self._sanitize_value(return_value) if return_value else None, exception=exception, duration_ms=duration_ms, ) def _sanitize_value(self, value: Any, max_len: int = 200) -> Any: """Sanitize a value for storage (avoid huge objects).""" if value is None: return None # Numpy arrays if hasattr(value, 'shape'): return f"<array shape={value.shape} dtype={value.dtype}>" # Tensors if hasattr(value, 'size') and hasattr(value, 'dtype'): return f"<tensor size={value.size()} dtype={value.dtype}>" # Large strings if isinstance(value, str) and len(value) > max_len: return value[:max_len] + "..." # Lists/dicts if isinstance(value, (list, dict)): s = str(value) if len(s) > max_len: return s[:max_len] + "..." return value # Primitives if isinstance(value, (int, float, bool, str)): return value # Fallback: type name return f"<{type(value).__name__}>" # ========================================================================= # CAUSATION TRACING (via cascade-lattice) # ========================================================================= def find_root_causes(self, event_id: str) -> RootCauseAnalysis: """ Find the root causes of an event (e.g., what caused this crash?). Uses cascade-lattice's backwards tracing to find the origin. """ return self.tracer.find_root_causes(event_id) def analyze_impact(self, event_id: str) -> ImpactAnalysis: """ Analyze the downstream impact of an event. "What did this bug affect?" """ return self.tracer.analyze_impact(event_id) def trace_backwards(self, event_id: str, max_depth: int = 100): """Trace what led to this event.""" return self.tracer.trace_backwards(event_id, max_depth) def trace_forwards(self, event_id: str, max_depth: int = 100): """Trace what this event caused.""" return self.tracer.trace_forwards(event_id, max_depth) # ========================================================================= # BUG DETECTION # ========================================================================= def detect_bugs(self) -> List[BugSignature]: """ Run all bug detection patterns on collected events. """ self._detected_bugs = [] for detector in self._bug_patterns: try: bugs = detector() self._detected_bugs.extend(bugs) except Exception as e: print(f"[DIAG] Bug detector {detector.__name__} failed: {e}") return self._detected_bugs def _detect_null_reference(self) -> List[BugSignature]: """Detect null/None reference patterns.""" bugs = [] for event in self.graph.get_recent_events(1000): if event.event_type == "function_exception": exc = event.data.get("exception", "") if "NoneType" in exc or "null" in exc.lower(): bugs.append(BugSignature( bug_type="null_reference", severity="error", evidence=[exc], affected_events=[event.event_id], confidence=0.9, )) return bugs def _detect_type_errors(self) -> List[BugSignature]: """Detect type mismatch patterns.""" bugs = [] for event in self.graph.get_recent_events(1000): if event.event_type == "function_exception": exc = event.data.get("exception", "") if "TypeError" in exc or "type" in exc.lower(): bugs.append(BugSignature( bug_type="type_mismatch", severity="error", evidence=[exc], affected_events=[event.event_id], confidence=0.85, )) return bugs def _detect_recursion_depth(self) -> List[BugSignature]: """Detect excessive recursion.""" bugs = [] # Find events with high call depth for event in self.graph.get_recent_events(1000): if hasattr(event, 'call_stack_depth') and event.call_stack_depth > 50: bugs.append(BugSignature( bug_type="deep_recursion", severity="warning", evidence=[f"Call stack depth: {event.call_stack_depth}"], affected_events=[event.event_id], confidence=0.7, )) return bugs def _detect_slow_functions(self) -> List[BugSignature]: """Detect unusually slow functions.""" bugs = [] for event in self.graph.get_recent_events(1000): if event.event_type == "function_return": duration = event.data.get("duration_ms", 0) if duration > 1000: # > 1 second bugs.append(BugSignature( bug_type="slow_function", severity="warning", evidence=[f"Duration: {duration:.1f}ms"], affected_events=[event.event_id], confidence=0.8, )) return bugs def _detect_exception_patterns(self) -> List[BugSignature]: """Detect recurring exception patterns.""" bugs = [] # Group exceptions by type exception_counts: Dict[str, List[str]] = {} for event in self.graph.get_recent_events(1000): if event.event_type == "function_exception": exc = event.data.get("exception", "unknown") if exc not in exception_counts: exception_counts[exc] = [] exception_counts[exc].append(event.event_id) # Flag recurring exceptions for exc_type, event_ids in exception_counts.items(): if len(event_ids) > 3: bugs.append(BugSignature( bug_type="recurring_exception", severity="error", evidence=[f"{exc_type} occurred {len(event_ids)} times"], affected_events=event_ids, confidence=0.9, )) return bugs # ========================================================================= # REPORTING # ========================================================================= def get_summary(self) -> Dict[str, Any]: """Get execution summary.""" return { "name": self.name, "total_events": self._event_count, "error_count": self._error_count, "bugs_detected": len(self._detected_bugs), "graph_nodes": len(self.graph._events), "graph_links": len(self.graph._links), } def get_error_chain(self, error_event_id: str) -> str: """ Get a human-readable error chain from root cause to error. """ analysis = self.find_root_causes(error_event_id) if not analysis.chains: return "No causal chain found" lines = ["ERROR CHAIN ANALYSIS", "=" * 50] # Take the deepest chain (most likely root cause) chain = analysis.chains[0] for i, event in enumerate(chain.events): prefix = " " * i if event.event_type == "function_exception": lines.append(f"{prefix}❌ {event.component}.{event.data.get('function', '?')}") lines.append(f"{prefix} Exception: {event.data.get('exception', '?')}") elif event.event_type == "function_entry": lines.append(f"{prefix}→ {event.component}.{event.data.get('function', '?')}") elif event.event_type == "function_return": lines.append(f"{prefix}← {event.component}.{event.data.get('function', '?')}") return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299"""CASCADE Diagnostics Demo - Exposing bugs with tracing.
This demonstrates how to use the cascade.diagnostics moduleto trace through code and expose issues."""
import syssys.path.insert(0, "F:/End-Game/github-pypi-lattice")
from cascade.diagnostics import ( diagnose, CodeTracer, BugDetector, ExecutionMonitor, DiagnosticEngine, monitor,)
# =============================================================================# DEMO 1: Trace function execution and find root causes# =============================================================================
print("=" * 60)print("DEMO 1: Function Execution Tracing")print("=" * 60)
tracer = CodeTracer(name="demo_tracer")
@tracer.tracedef calculate_average(numbers): """Calculate average - but has a bug with empty lists!""" total = sum(numbers) return total / len(numbers) # Bug: ZeroDivisionError if empty
@tracer.tracedef process_data(data): """Process data and return stats.""" averages = [] for dataset in data: avg = calculate_average(dataset) averages.append(avg) return averages
# Run with normal dataprint("\n1a. Running with valid data...")try: result = process_data([[1, 2, 3], [4, 5, 6]]) print(f" Result: {result}")except Exception as e: print(f" Error: {e}")
# Run with buggy data (empty list)print("\n1b. Running with empty list (trigger bug)...")try: result = process_data([[1, 2, 3], []]) # Empty list causes ZeroDivisionError print(f" Result: {result}")except Exception as e: print(f" Error: {e}")
# Check detected bugsprint("\n1c. Detecting bugs from execution trace...")bugs = tracer.detect_bugs()for bug in bugs: print(f" - {bug.bug_type}: {bug.evidence}")
# Print summaryprint("\n1d. Tracer Summary:")summary = tracer.get_summary()for key, value in summary.items(): print(f" {key}: {value}")
# =============================================================================# DEMO 2: Static code analysis with BugDetector# =============================================================================
print("\n" + "=" * 60)print("DEMO 2: Static Code Analysis")print("=" * 60)
# Create a buggy file for demonstrationbuggy_code = '''def process_user(user_data): """Process user - has several bugs!""" # Bug 1: Bare except try: name = user_data["name"] except: pass # Bug 2: Mutable default argument def add_item(item, items=[]): items.append(item) return items # Bug 3: Hardcoded password password = "admin123" # Bug 4: SQL injection risk cursor.execute("SELECT * FROM users WHERE name = '%s'" % name) # Bug 5: Comparing to None with == if user_data == None: return # Bug 6: File without context manager f = open("data.txt", "r") data = f.read() return name
def unreachable_example(): """Has unreachable code.""" return 42 print("This never runs") # Unreachable'''
# Write buggy code to temp fileimport tempfileimport os
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f: f.write(buggy_code) buggy_file = f.name
print(f"\n2a. Scanning buggy code file...")detector = BugDetector()issues = detector.scan_file(buggy_file)
print(f" Found {len(issues)} issues:\n")for issue in sorted(issues, key=lambda i: ["critical", "error", "warning", "info"].index(i.severity) if i.severity in ["critical", "error", "warning", "info"] else 99): severity_icon = {"critical": "🔴", "error": "❌", "warning": "⚠️", "info": "ℹ️"}.get(issue.severity, "•") print(f" {severity_icon} [{issue.severity}] Line {issue.line_number}: {issue.message}") if issue.suggestion: print(f" 💡 {issue.suggestion}")
# Clean up temp fileos.unlink(buggy_file)
print("\n2b. Bug Detection Summary:")print(detector.get_report())
# =============================================================================# DEMO 3: Real-time Execution Monitoring# =============================================================================
print("\n" + "=" * 60)print("DEMO 3: Real-time Execution Monitoring")print("=" * 60)
print("\n3a. Monitoring execution with anomaly detection...")
monitor_instance = ExecutionMonitor()
def recursive_fib(n): """Intentionally slow recursive fibonacci.""" if n <= 1: return n return recursive_fib(n - 1) + recursive_fib(n - 2)
def raise_error(): """Function that raises an error.""" raise ValueError("Intentional test error")
with monitor_instance.monitoring(): # Normal computation result = recursive_fib(15) # Error (intentionally caught and ignored for demo) try: raise_error() except ValueError: pass # Expected - demonstrating exception capture
print(f" Frames captured: {len(monitor_instance.frames)}")print(f" Anomalies detected: {len(monitor_instance.anomalies)}")
print("\n3b. Execution Monitoring Report:")print(monitor_instance.get_report())
# =============================================================================# DEMO 4: Full Diagnostic Engine# =============================================================================
print("\n" + "=" * 60)print("DEMO 4: Full Diagnostic Engine")print("=" * 60)
print("\n4a. Running full diagnostics on a function...")
def buggy_function(x, y): """Function with potential issues.""" if x is None: raise ValueError("x cannot be None") result = x / y # Potential ZeroDivisionError return result
engine = DiagnosticEngine()
# Analyze the function executiontry: report = engine.analyze_execution(buggy_function, 10, 2) print(f" Report generated: {report.report_id}") print(f" Total findings: {len(report.findings)}")except Exception as e: print(f" Analysis captured error: {e}")
# Analyze with errorprint("\n4b. Analyzing execution that triggers error...")try: report = engine.analyze_execution(buggy_function, 10, 0)except ZeroDivisionError: # The error still propagates but we captured the trace print(" Error captured in execution trace")
# =============================================================================# DEMO 5: The diagnose() convenience function# =============================================================================
print("\n" + "=" * 60)print("DEMO 5: diagnose() Convenience Function")print("=" * 60)
# Create another temp filesimple_code = '''def hello(): try: pass # Empty except coming except: pass'''
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f: f.write(simple_code) simple_file = f.name
print(f"\n5a. Quick diagnosis of a file...")report = diagnose(simple_file)print(f" Issues found: {len(report.findings)}")
for finding in report.findings: print(f" - {finding.title}: {finding.description}")
os.unlink(simple_file)
# =============================================================================# SUMMARY# =============================================================================
print("\n" + "=" * 60)print("CASCADE DIAGNOSTICS - Summary")print("=" * 60)
print("""The cascade.diagnostics module repurposes cascade-lattice for debugging:
1. CodeTracer - Trace function execution with causation graph - @tracer.trace decorator captures every call - find_root_causes() traces backwards from errors - analyze_impact() predicts what a bug affects - detect_bugs() finds patterns in execution
2. BugDetector - Static analysis with AST pattern matching - Detects: null refs, bare excepts, SQL injection, etc. - scan_file() / scan_directory() for batch analysis - Custom patterns can be registered
3. ExecutionMonitor - Real-time sys.settrace monitoring - Captures every function call during execution - Detects anomalies: slow functions, deep recursion, repeated errors - get_hotspots() finds performance bottlenecks
4. DiagnosticEngine - Unified diagnostic reports - Combines all analyzers - Markdown/JSON output - Severity-ranked findings with suggestions
5. diagnose() - One-line convenience function - Works on files, directories, or functions
The core insight: Events = execution points, Links = causation.Trace backwards from bugs to find root causes.Trace forwards from changes to predict impact.""")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473"""CASCADE Execution Monitor - Monitor live code execution.
Wraps Python execution similar to how cascade.observe wraps processes.Captures execution flow, exceptions, and anomalies in real-time."""
import sysimport timeimport threadingimport tracebackimport functoolsfrom typing import Any, Dict, List, Optional, Callable, Set, Tuplefrom dataclasses import dataclass, fieldfrom contextlib import contextmanagerimport queue
from cascade.core.event import Event, CausationLinkfrom cascade.core.graph import CausationGraphfrom cascade.core.adapter import SymbioticAdapter
@dataclassclass ExecutionFrame: """A frame in the execution trace.""" frame_id: str function_name: str file_path: str line_number: int local_vars: Dict[str, str] # Sanitized string representations timestamp: float duration_ms: Optional[float] = None exception: Optional[str] = None
@dataclassclass Anomaly: """An execution anomaly detected during monitoring.""" anomaly_type: str description: str severity: str frame_id: str timestamp: float context: Dict[str, Any] = field(default_factory=dict)
class ExecutionMonitor: """ Monitor live code execution and capture anomalies. Uses sys.settrace to capture every function call, return, and exception. Integrates with cascade-lattice's causation graph for tracing. Usage: monitor = ExecutionMonitor() with monitor.monitoring(): # Your code here result = my_function() # After execution: monitor.get_anomalies() monitor.get_execution_trace() """ def __init__(self, capture_locals: bool = True, max_depth: int = 100, exclude_modules: Optional[Set[str]] = None): self.capture_locals = capture_locals self.max_depth = max_depth self.exclude_modules = exclude_modules or { 'cascade', 'threading', 'queue', 'logging', 'importlib', '_frozen_importlib', 'posixpath', 'genericpath', } # Execution tracking self.frames: List[ExecutionFrame] = [] self.anomalies: List[Anomaly] = [] self.call_stack: List[str] = [] # Causation graph self.graph = CausationGraph() self.adapter = SymbioticAdapter() # Thresholds for anomaly detection self.slow_threshold_ms = 100 self.deep_recursion_threshold = 50 # State self._monitoring = False self._lock = threading.RLock() self._frame_counter = 0 self._function_times: Dict[str, List[float]] = {} self._prev_trace = None @contextmanager def monitoring(self): """Context manager for monitoring execution.""" self.start() try: yield self finally: self.stop() def start(self): """Start execution monitoring.""" if self._monitoring: return self._monitoring = True self._prev_trace = sys.gettrace() sys.settrace(self._trace_calls) threading.settrace(self._trace_calls) def stop(self): """Stop execution monitoring.""" if not self._monitoring: return self._monitoring = False sys.settrace(self._prev_trace) threading.settrace(None) # Analyze collected data for anomalies self._analyze_for_anomalies() def _trace_calls(self, frame, event, arg): """Trace function for sys.settrace.""" if not self._monitoring: return None # Filter out excluded modules code = frame.f_code module = frame.f_globals.get('__name__', '') if any(module.startswith(exc) for exc in self.exclude_modules): return None # Check depth if len(self.call_stack) > self.max_depth: return None try: if event == 'call': self._handle_call(frame, code) elif event == 'return': self._handle_return(frame, code, arg) elif event == 'exception': self._handle_exception(frame, code, arg) except Exception: # Don't let tracing errors affect the program pass return self._trace_calls def _handle_call(self, frame, code): """Handle function call event.""" with self._lock: self._frame_counter += 1 frame_id = f"frame_{self._frame_counter}" # Capture local variables local_vars = {} if self.capture_locals: for name, value in list(frame.f_locals.items())[:20]: local_vars[name] = self._sanitize_value(value) exec_frame = ExecutionFrame( frame_id=frame_id, function_name=code.co_name, file_path=code.co_filename, line_number=frame.f_lineno, local_vars=local_vars, timestamp=time.time(), ) self.frames.append(exec_frame) # Create causation link to caller if self.call_stack: caller_id = self.call_stack[-1] link = CausationLink( from_event=caller_id, to_event=frame_id, causation_type="call", strength=1.0, explanation=f"Called {code.co_name}" ) self.graph.add_link(link) self.call_stack.append(frame_id) # Track function timing func_key = f"{code.co_filename}:{code.co_name}" if func_key not in self._function_times: self._function_times[func_key] = [] def _handle_return(self, frame, code, return_value): """Handle function return event.""" with self._lock: if not self.call_stack: return frame_id = self.call_stack.pop() # Find the frame and update duration for exec_frame in reversed(self.frames): if exec_frame.frame_id == frame_id: exec_frame.duration_ms = (time.time() - exec_frame.timestamp) * 1000 # Track timing func_key = f"{code.co_filename}:{code.co_name}" if func_key in self._function_times: self._function_times[func_key].append(exec_frame.duration_ms) break def _handle_exception(self, frame, code, arg): """Handle exception event.""" exc_type, exc_value, exc_tb = arg with self._lock: frame_id = self.call_stack[-1] if self.call_stack else f"frame_{self._frame_counter}" # Update frame with exception for exec_frame in reversed(self.frames): if exec_frame.frame_id == frame_id: exec_frame.exception = f"{exc_type.__name__}: {exc_value}" break # Record as anomaly self.anomalies.append(Anomaly( anomaly_type="exception", description=f"{exc_type.__name__}: {exc_value}", severity="error", frame_id=frame_id, timestamp=time.time(), context={ "exception_type": exc_type.__name__, "exception_message": str(exc_value), "function": code.co_name, "file": code.co_filename, "line": frame.f_lineno, }, )) def _analyze_for_anomalies(self): """Analyze collected data for additional anomalies.""" # Check for slow functions for func_key, times in self._function_times.items(): if times: avg_time = sum(times) / len(times) max_time = max(times) if max_time > self.slow_threshold_ms: self.anomalies.append(Anomaly( anomaly_type="slow_execution", description=f"Slow function: {func_key} (max: {max_time:.1f}ms, avg: {avg_time:.1f}ms)", severity="warning", frame_id="", timestamp=time.time(), context={ "function": func_key, "max_time_ms": max_time, "avg_time_ms": avg_time, "call_count": len(times), }, )) # Check for deep recursion max_depth = max((len(self.call_stack) for f in self.frames), default=0) if max_depth > self.deep_recursion_threshold: self.anomalies.append(Anomaly( anomaly_type="deep_recursion", description=f"Deep call stack detected: {max_depth} frames", severity="warning", frame_id="", timestamp=time.time(), context={"max_depth": max_depth}, )) # Check for repeated exceptions exception_counts: Dict[str, int] = {} for anomaly in self.anomalies: if anomaly.anomaly_type == "exception": exc_type = anomaly.context.get("exception_type", "unknown") exception_counts[exc_type] = exception_counts.get(exc_type, 0) + 1 for exc_type, count in exception_counts.items(): if count > 3: self.anomalies.append(Anomaly( anomaly_type="repeated_exception", description=f"{exc_type} occurred {count} times", severity="error", frame_id="", timestamp=time.time(), context={"exception_type": exc_type, "count": count}, )) def _sanitize_value(self, value: Any, max_len: int = 100) -> str: """Convert value to safe string representation.""" try: if value is None: return "None" # Numpy arrays if hasattr(value, 'shape'): return f"<array {value.shape}>" # Tensors if hasattr(value, 'size') and callable(value.size): return f"<tensor {value.size()}>" # Large collections if isinstance(value, (list, dict, set)): s = str(value) if len(s) > max_len: return s[:max_len] + "..." return s # Strings if isinstance(value, str): if len(value) > max_len: return value[:max_len] + "..." return repr(value) # Primitives if isinstance(value, (int, float, bool)): return str(value) # Fallback return f"<{type(value).__name__}>" except Exception: return "<error>" # ========================================================================= # QUERIES # ========================================================================= def get_anomalies(self, severity: Optional[str] = None) -> List[Anomaly]: """Get detected anomalies, optionally filtered by severity.""" if severity: return [a for a in self.anomalies if a.severity == severity] return list(self.anomalies) def get_execution_trace(self) -> List[ExecutionFrame]: """Get the execution trace.""" return list(self.frames) def get_call_graph(self) -> Dict[str, List[str]]: """Get the call graph as adjacency list.""" graph: Dict[str, List[str]] = {} for link in self.graph._links: if link.from_event not in graph: graph[link.from_event] = [] graph[link.from_event].append(link.to_event) return graph def get_hotspots(self, top_n: int = 10) -> List[Tuple[str, float, int]]: """Get the hottest functions by total time spent.""" totals: Dict[str, Tuple[float, int]] = {} for func_key, times in self._function_times.items(): if times: totals[func_key] = (sum(times), len(times)) sorted_funcs = sorted(totals.items(), key=lambda x: x[1][0], reverse=True) return [(func, total, count) for func, (total, count) in sorted_funcs[:top_n]] # ========================================================================= # REPORTING # ========================================================================= def get_summary(self) -> Dict[str, Any]: """Get monitoring summary.""" return { "total_frames": len(self.frames), "total_anomalies": len(self.anomalies), "anomalies_by_type": self._count_by_key(self.anomalies, lambda a: a.anomaly_type), "anomalies_by_severity": self._count_by_key(self.anomalies, lambda a: a.severity), "functions_traced": len(self._function_times), } def _count_by_key(self, items, key_func) -> Dict[str, int]: """Count items by key function.""" counts: Dict[str, int] = {} for item in items: key = key_func(item) counts[key] = counts.get(key, 0) + 1 return counts def get_report(self) -> str: """Generate a human-readable report.""" lines = [ "EXECUTION MONITORING REPORT", "=" * 60, f"Frames captured: {len(self.frames)}", f"Functions traced: {len(self._function_times)}", f"Anomalies detected: {len(self.anomalies)}", "", ] # Anomalies by severity if self.anomalies: lines.append("ANOMALIES") lines.append("-" * 40) severity_icons = {"critical": "🔴", "error": "❌", "warning": "⚠️", "info": "ℹ️"} for anomaly in sorted(self.anomalies, key=lambda a: ["critical", "error", "warning", "info"].index(a.severity) if a.severity in ["critical", "error", "warning", "info"] else 99): icon = severity_icons.get(anomaly.severity, "•") lines.append(f" {icon} [{anomaly.anomaly_type}] {anomaly.description}") lines.append("") # Hotspots hotspots = self.get_hotspots(5) if hotspots: lines.append("PERFORMANCE HOTSPOTS") lines.append("-" * 40) for func, total_ms, count in hotspots: avg_ms = total_ms / count if count else 0 lines.append(f" {func}") lines.append(f" Total: {total_ms:.1f}ms | Calls: {count} | Avg: {avg_ms:.1f}ms") lines.append("") return "\n".join(lines)
# =============================================================================# CONVENIENCE DECORATORS# =============================================================================
def monitor(func: Callable = None, **kwargs) -> Callable: """ Decorator to monitor a function's execution. Usage: @monitor def my_function(): ... # Access monitoring results my_function._monitor_results """ def decorator(fn: Callable) -> Callable: @functools.wraps(fn) def wrapper(*args, **call_kwargs): monitor = ExecutionMonitor(**kwargs) with monitor.monitoring(): result = fn(*args, **call_kwargs) # Attach results to function wrapper._monitor_results = { "anomalies": monitor.get_anomalies(), "summary": monitor.get_summary(), "report": monitor.get_report(), } return result wrapper._monitor_results = None return wrapper if func is not None: return decorator(func) return decorator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432"""CASCADE Diagnostic Report - Generate comprehensive diagnostic reports.
Combines:- CodeTracer execution traces- BugDetector static analysis- ExecutionMonitor runtime anomalies- GhostLog forensic reconstruction
Into a unified diagnostic report."""
import timeimport jsonimport hashlibfrom typing import Any, Dict, List, Optional, Setfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom datetime import datetime
from cascade.core.graph import CausationGraphfrom cascade.forensics.analyzer import DataForensics, GhostLog
@dataclassclass DiagnosticFinding: """A single diagnostic finding.""" finding_id: str category: str # "static", "runtime", "forensic", "trace" severity: str # "critical", "error", "warning", "info" title: str description: str location: Optional[Dict[str, Any]] = None # file, line, function evidence: List[str] = field(default_factory=list) related_findings: List[str] = field(default_factory=list) suggestions: List[str] = field(default_factory=list) confidence: float = 1.0 timestamp: float = field(default_factory=time.time)
@dataclass class DiagnosticReport: """ A comprehensive diagnostic report. Aggregates findings from multiple sources: - Static analysis (BugDetector) - Runtime monitoring (ExecutionMonitor) - Execution tracing (CodeTracer) - Forensic analysis (GhostLog) """ report_id: str title: str created_at: float target: str # File, directory, or module analyzed findings: List[DiagnosticFinding] = field(default_factory=list) summary: Dict[str, Any] = field(default_factory=dict) # Source data static_analysis: Dict[str, Any] = field(default_factory=dict) runtime_analysis: Dict[str, Any] = field(default_factory=dict) trace_analysis: Dict[str, Any] = field(default_factory=dict) forensic_analysis: Dict[str, Any] = field(default_factory=dict) def add_finding(self, finding: DiagnosticFinding): """Add a finding to the report.""" self.findings.append(finding) def get_findings_by_severity(self, severity: str) -> List[DiagnosticFinding]: """Get findings filtered by severity.""" return [f for f in self.findings if f.severity == severity] def get_findings_by_category(self, category: str) -> List[DiagnosticFinding]: """Get findings filtered by category.""" return [f for f in self.findings if f.category == category] def compute_summary(self): """Compute summary statistics.""" self.summary = { "total_findings": len(self.findings), "by_severity": {}, "by_category": {}, "critical_count": 0, "has_critical": False, } for finding in self.findings: # Count by severity sev = finding.severity self.summary["by_severity"][sev] = self.summary["by_severity"].get(sev, 0) + 1 # Count by category cat = finding.category self.summary["by_category"][cat] = self.summary["by_category"].get(cat, 0) + 1 self.summary["critical_count"] = self.summary["by_severity"].get("critical", 0) self.summary["has_critical"] = self.summary["critical_count"] > 0 def to_dict(self) -> Dict[str, Any]: """Convert to dictionary.""" return { "report_id": self.report_id, "title": self.title, "created_at": self.created_at, "target": self.target, "summary": self.summary, "findings": [ { "id": f.finding_id, "category": f.category, "severity": f.severity, "title": f.title, "description": f.description, "location": f.location, "evidence": f.evidence, "suggestions": f.suggestions, "confidence": f.confidence, } for f in self.findings ], "static_analysis": self.static_analysis, "runtime_analysis": self.runtime_analysis, "trace_analysis": self.trace_analysis, "forensic_analysis": self.forensic_analysis, } def to_json(self, indent: int = 2) -> str: """Convert to JSON string.""" return json.dumps(self.to_dict(), indent=indent, default=str) def save(self, path: str): """Save report to file.""" with open(path, 'w') as f: f.write(self.to_json()) @classmethod def load(cls, path: str) -> "DiagnosticReport": """Load report from file.""" with open(path, 'r') as f: data = json.load(f) report = cls( report_id=data["report_id"], title=data["title"], created_at=data["created_at"], target=data["target"], ) report.summary = data.get("summary", {}) report.static_analysis = data.get("static_analysis", {}) report.runtime_analysis = data.get("runtime_analysis", {}) report.trace_analysis = data.get("trace_analysis", {}) report.forensic_analysis = data.get("forensic_analysis", {}) for f_data in data.get("findings", []): finding = DiagnosticFinding( finding_id=f_data["id"], category=f_data["category"], severity=f_data["severity"], title=f_data["title"], description=f_data["description"], location=f_data.get("location"), evidence=f_data.get("evidence", []), suggestions=f_data.get("suggestions", []), confidence=f_data.get("confidence", 1.0), ) report.findings.append(finding) return report
class DiagnosticEngine: """ Engine for running comprehensive diagnostics. Usage: engine = DiagnosticEngine() # Analyze a file report = engine.analyze_file("path/to/file.py") # Analyze a directory report = engine.analyze_directory("path/to/project") # Analyze with runtime monitoring report = engine.analyze_execution(my_function, args) # Print report print(report.to_markdown()) """ def __init__(self): from .code_tracer import CodeTracer from .bug_detector import BugDetector from .execution_monitor import ExecutionMonitor self.tracer = CodeTracer() self.detector = BugDetector() self.monitor_class = ExecutionMonitor self._report_counter = 0 def analyze_file(self, file_path: str) -> DiagnosticReport: """Run static analysis on a single file.""" self._report_counter += 1 report = DiagnosticReport( report_id=self._generate_report_id(file_path), title=f"Diagnostic Report: {Path(file_path).name}", created_at=time.time(), target=file_path, ) # Run static analysis issues = self.detector.scan_file(file_path) for issue in issues: finding = DiagnosticFinding( finding_id=issue.issue_id, category="static", severity=issue.severity, title=issue.pattern_name.replace("_", " ").title(), description=issue.message, location={ "file": issue.file_path, "line": issue.line_number, "column": issue.column, }, evidence=[issue.code_snippet] if issue.code_snippet else [], suggestions=[issue.suggestion] if issue.suggestion else [], confidence=issue.confidence, ) report.add_finding(finding) report.static_analysis = self.detector.get_summary() report.compute_summary() return report def analyze_directory(self, dir_path: str, recursive: bool = True) -> DiagnosticReport: """Run static analysis on a directory.""" self._report_counter += 1 report = DiagnosticReport( report_id=self._generate_report_id(dir_path), title=f"Diagnostic Report: {Path(dir_path).name}", created_at=time.time(), target=dir_path, ) # Run static analysis issues = self.detector.scan_directory(dir_path, recursive) for issue in issues: finding = DiagnosticFinding( finding_id=issue.issue_id, category="static", severity=issue.severity, title=issue.pattern_name.replace("_", " ").title(), description=issue.message, location={ "file": issue.file_path, "line": issue.line_number, "column": issue.column, }, evidence=[issue.code_snippet] if issue.code_snippet else [], suggestions=[issue.suggestion] if issue.suggestion else [], confidence=issue.confidence, ) report.add_finding(finding) report.static_analysis = self.detector.get_summary() report.compute_summary() return report def analyze_execution(self, func, *args, **kwargs) -> DiagnosticReport: """Run diagnostics on function execution.""" self._report_counter += 1 func_name = getattr(func, '__name__', str(func)) report = DiagnosticReport( report_id=self._generate_report_id(func_name), title=f"Execution Diagnostic: {func_name}", created_at=time.time(), target=func_name, ) # Create a monitor for this execution monitor = self.monitor_class() result = None exception = None with monitor.monitoring(): try: result = func(*args, **kwargs) except Exception as e: exception = e # Convert anomalies to findings for anomaly in monitor.get_anomalies(): finding = DiagnosticFinding( finding_id=f"anomaly_{anomaly.frame_id}_{anomaly.timestamp}", category="runtime", severity=anomaly.severity, title=anomaly.anomaly_type.replace("_", " ").title(), description=anomaly.description, location=anomaly.context, confidence=1.0, ) report.add_finding(finding) # Add execution summary report.runtime_analysis = monitor.get_summary() report.runtime_analysis["hotspots"] = [ {"function": f, "total_ms": t, "calls": c} for f, t, c in monitor.get_hotspots(10) ] if exception: report.runtime_analysis["exception"] = str(exception) report.compute_summary() return report def _generate_report_id(self, target: str) -> str: """Generate a unique report ID.""" content = f"{target}:{time.time()}:{self._report_counter}" return hashlib.sha256(content.encode()).hexdigest()[:16] def to_markdown(self, report: DiagnosticReport) -> str: """Convert a report to Markdown format.""" lines = [ f"# {report.title}", "", f"**Report ID:** `{report.report_id}`", f"**Generated:** {datetime.fromtimestamp(report.created_at).isoformat()}", f"**Target:** `{report.target}`", "", "## Summary", "", f"- **Total Findings:** {report.summary.get('total_findings', 0)}", ] # Severity breakdown by_severity = report.summary.get("by_severity", {}) if by_severity: lines.append("") lines.append("### By Severity") lines.append("") icons = {"critical": "🔴", "error": "❌", "warning": "⚠️", "info": "ℹ️"} for sev in ["critical", "error", "warning", "info"]: count = by_severity.get(sev, 0) if count: lines.append(f"- {icons.get(sev, '•')} **{sev.title()}:** {count}") # Findings if report.findings: lines.extend(["", "## Findings", ""]) for finding in sorted(report.findings, key=lambda f: ["critical", "error", "warning", "info"].index(f.severity) if f.severity in ["critical", "error", "warning", "info"] else 99): icon = {"critical": "🔴", "error": "❌", "warning": "⚠️", "info": "ℹ️"}.get(finding.severity, "•") lines.append(f"### {icon} {finding.title}") lines.append("") lines.append(f"**Severity:** {finding.severity} | **Category:** {finding.category}") lines.append("") lines.append(finding.description) if finding.location: loc = finding.location if "file" in loc: lines.append("") lines.append(f"**Location:** `{loc.get('file', '')}:{loc.get('line', '')}`") if finding.evidence: lines.append("") lines.append("**Evidence:**") for ev in finding.evidence: lines.append(f"```") lines.append(ev) lines.append(f"```") if finding.suggestions: lines.append("") lines.append("**Suggestions:**") for sug in finding.suggestions: lines.append(f"- {sug}") lines.append("") return "\n".join(lines)
# =============================================================================# CONVENIENCE FUNCTION# =============================================================================
def diagnose(target, **kwargs) -> DiagnosticReport: """ Convenience function to run diagnostics. Usage: # Analyze a file report = diagnose("path/to/file.py") # Analyze a directory report = diagnose("path/to/project/") # Analyze a function report = diagnose(my_function, arg1, arg2) """ engine = DiagnosticEngine() if callable(target): # It's a function return engine.analyze_execution(target, **kwargs) elif isinstance(target, str): path = Path(target) if path.is_file(): return engine.analyze_file(target) elif path.is_dir(): return engine.analyze_directory(target) raise ValueError(f"Cannot diagnose target: {target}")4 unmodified lines5678910111 unmodified line131415161718194 unmodified lines[project]name = "cascade-lattice"dynamic = ["version"]description = "Universal AI provenance layer — cryptographic receipts for every call, with HOLD inference halt protocol"readme = "README.md"license = "MIT"authors = [1 unmodified line]keywords = ["ai", "ml", "provenance", "observability", "llm", "tracing","cryptographic", "receipts", "monitoring", "hold-protocol"]classifiers = ["Development Status :: 4 - Beta",4 unmodified lines5678910111 unmodified line13141516171819204 unmodified lines[project]name = "cascade-lattice"dynamic = ["version"]description = "Universal AI provenance layer — cryptographic receipts for every call, HOLD inference halt protocol, and code diagnostics"readme = "README.md"license = "MIT"authors = [1 unmodified line]keywords = ["ai", "ml", "provenance", "observability", "llm", "tracing","cryptographic", "receipts", "monitoring", "hold-protocol","diagnostics", "debugging", "bug-detection", "static-analysis"]classifiers = ["Development Status :: 4 - Beta",
README.md+40-1
cascade/__init__.py+6-1
cascade/diagnostics/__init__.pyAdded+73
cascade/diagnostics/bug_detector.pyAdded+590
cascade/diagnostics/code_tracer.pyAdded+512
cascade/diagnostics/demo.pyAdded+299
cascade/diagnostics/execution_monitor.pyAdded+473
cascade/diagnostics/report.pyAdded+432
pyproject.toml+3-2