python
import pandas as pd
import numpy as np
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass
from collections import defaultdict
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class Span:
service: str
operation: str
duration_ms: float
tags: Dict[str, Any] = None # e.g., {'db.query': '...', 'error': True, 'http.status_code': 500}
span_id: str = "" # For traceability
def __post_init__(self):
if self.tags is None:
self.tags = {}
@dataclass
class Trace:
trace_id: str
spans: List[Span]
total_duration_ms: float = 0.0
def __post_init__(self):
if self.total_duration_ms == 0.0:
self.total_duration_ms = sum(span.duration_ms for span in self.spans)
class P99OutlierRootCauseFinder:
"""
P99 Outlier Trace Root-Cause Finder.
Uses:
- **Heuristics**: Longest span, error-prone spans, tagged slow-ops (e.g., DB queries > threshold,
HTTP 5xx, high CPU/memory tags if present).
- **Correlation Mining**: Compares span durations in outliers vs. baselines (normal traces).
- High delta mean (outlier_mean / baseline_mean > ratio_threshold).
- Correlation coeff between span duration and total trace duration (across traces).
- Span contribution % > threshold.
Workflow:
1. Fit on historical traces: Compute P99 latency, baseline stats per span_type (service:operation).
2. Detect outliers: Traces > P99.
3. For outlier trace: Score root causes via heuristics + correlations.
"""
def __init__(
self,
p99_percentile: float = 99.0,
ratio_threshold: float = 3.0, # Outlier mean / baseline > 3x suspicious
contrib_threshold: float = 0.5, # Span contrib > 50% of total
corr_threshold: float = 0.7, # High correlation with total duration
error_keywords: List[str] = None,
slow_op_keywords: List[str] = None,
heuristic_weight: float = 0.4,
correlation_weight: float = 0.6
):
self.p99_percentile = p99_percentile
self.ratio_threshold = ratio_threshold
self.contrib_threshold = contrib_threshold
self.corr_threshold = corr_threshold
self.heuristic_weight = heuristic_weight
self.correlation_weight = correlation_weight
self.error_keywords = error_keywords or ['error', 'exception', 'timeout']
self.slow_op_keywords = slow_op_keywords or ['db.query', 'http.request', 'redis.get', 'external.call']
# Baselines
self.trace_durations: List[float] = []
self.span_stats: Dict[str, Dict[str, float]] = {} # span_type -> {'mean':, 'p95':, 'count':}
self.span_correlations: Dict[str, float] = {} # span_type -> corr with total_duration
self.p99_latency: Optional[float] = None
# For fitting correlations, we'll aggregate per-trace span durations
self.trace_span_matrix: Optional[pd.DataFrame] = None
def _get_span_type(self, span: Span) -> str:
return f"{span.service}:{span.operation}"
def _is_error_span(self, span: Span) -> bool:
tags_lower = {k.lower(): v for k, v in span.tags.items()}
return any(kw in tags_lower for kw in self.error_keywords) or tags_lower.get('error', False)
def _is_slow_op(self, span: Span) -> bool:
op_lower = span.operation.lower()
return any(kw in op_lower for kw in self.slow_op_keywords)
def fit(self, traces: List[Trace]) -> None:
"""Fit baselines from historical traces."""
if not traces:
raise ValueError("No traces provided for fitting.")
self.trace_durations = [t.total_duration_ms for t in traces]
self.p99_latency = np.percentile(self.trace_durations, self.p99_percentile)
logger.info(f"Fitted P99 latency: {self.p99_latency:.2f}ms from {len(traces)} traces")
# Aggregate span stats per type
all_spans = []
trace_data = []
span_types = set()
for trace in traces:
row = {'total_duration': trace.total_duration_ms}
for span in trace.spans:
span_type = self._get_span_type(span)
span_types.add(span_type)
all_spans.append({
'span_type': span_type,
'duration': span.duration_ms,
'trace_id': trace.trace_id
})
row[span_type] = row.get(span_type, 0) + span.duration_ms
trace_data.append(row)
# Span baselines
df_spans = pd.DataFrame(all_spans)
for stype in span_types:
subset = df_spans[df_spans['span_type'] == stype]
if len(subset) > 0:
self.span_stats[stype] = {
'mean': subset['duration'].mean(),
'p95': np.percentile(subset['duration'], 95),
'count': len(subset)
}
# Correlation mining: Create matrix of trace totals vs per-span sums
df_traces = pd.DataFrame(trace_data)
numeric_cols = [col for col in df_traces.columns if col != 'total_duration' and col in span_types]
df_traces_numeric = df_traces[['total_duration'] + numeric_cols].fillna(0)
for col in numeric_cols:
if col in df_traces_numeric.columns:
corr = df_traces_numeric['total_duration'].corr(df_traces_numeric[col])
self.span_correlations[col] = corr if not pd.isna(corr) else 0
self.trace_span_matrix = df_traces_numeric
logger.info(f"Baselines computed for {len(self.span_stats)} span types")
def is_outlier(self, trace: Trace) -> bool:
"""Check if trace is P99 outlier."""
return trace.total_duration_ms > self.p99_latency if self.p99_latency else False
def _heuristic_score(self, span: Span, total_duration: float) -> float:
"""Heuristic score for a span (0-1)."""
score = 0.0
duration = span.duration_ms
contrib = duration / total_duration
# Contribution
if contrib > self.contrib_threshold:
score += 0.3
# Relative to baseline
span_type = self._get_span_type(span)
baseline = self.span_stats.get(span_type, {}).get('p95', duration)
if duration > baseline * self.ratio_threshold:
score += 0.3
# Error
if self._is_error_span(span):
score += 0.2
# Slow op
if self._is_slow_op(span):
score += 0.1
return min(score, 1.0)
def _correlation_score(self, span_type: str, trace_duration: float, span_duration: float) -> float:
"""Correlation-based score (0-1)."""
score = 0.0
# Global corr
corr = self.span_correlations.get(span_type, 0)
if corr > self.corr_threshold:
score += 0.4
# Local ratio vs baseline mean
baseline_mean = self.span_stats.get(span_type, {}).get('mean', span_duration)
if baseline_mean > 0:
ratio = span_duration / baseline_mean
if ratio > self.ratio_threshold:
score += 0.4
# Outlier-specific: compare to trace's "expected" based on corr
expected = corr * trace_duration # Rough linear approx
if span_duration > expected * self.ratio_threshold:
score += 0.2
return min(score, 1.0)
def find_root_causes(
self,
outlier_trace: Trace,
top_k: int = 5
) -> List[Dict[str, Any]]:
"""
Find top root causes for an outlier trace.
Returns: List of dicts sorted by score desc, e.g.,
[{'span_type': 'user-service:getUser', 'span_id': '...', 'score': 0.92,
'reason': 'High contrib (60%) + 4x baseline + error', 'duration_ms': 1500}]
"""
if not self.p99_latency:
raise ValueError("Must fit() before finding root causes.")
if not self.is_outlier(outlier_trace):
logger.warning(f"Trace {outlier_trace.trace_id} is not a P99 outlier.")
candidates = []
total_dur = outlier_trace.total_duration_ms
for span in outlier_trace.spans:
span_type = self._get_span_type(span)
heur_score = self._heuristic_score(span, total_dur)
corr_score = self._correlation_score(span_type, total_dur, span.duration_ms)
total_score = (self.heuristic_weight * heur_score +
self.correlation_weight * corr_score)
reasons = []
contrib = span.duration_ms / total_dur
if contrib > self.contrib_threshold:
reasons.append(f"High contrib ({contrib:.1%})")
if self._is_error_span(span):
reasons.append("Error tagged")
if self._is_slow_op(span):
reasons.append("Slow op type")
baseline_p95 = self.span_stats.get(span_type, {}).get('p95', 0)
if span.duration_ms > baseline_p95 * self.ratio_threshold:
reasons.append(f">{self.ratio_threshold}x P95 baseline")
corr = self.span_correlations.get(span_type, 0)
if corr > self.corr_threshold:
reasons.append(f"High corr ({corr:.2f}) w/ total dur")
candidates.append({
'span_id': span.span_id,
'span_type': span_type,
'service': span.service,
'operation': span.operation,
'duration_ms': span.duration_ms,
'contrib_pct': contrib * 100,
'score': total_score,
'reasons': reasons,
'tags': span.tags
})
# Sort by score desc
candidates.sort(key=lambda x: x['score'], reverse=True)
return candidates[:top_k]
# Example Usage & Demo
def demo():
# Synthetic traces (in real: load from Jaeger/Zipkin API)
traces = [
Trace(trace_id="normal1", spans=[
Span("user-svc", "getUser", 10),
Span("db-svc", "query", 20)
]),
# ... many normals
] * 100 # 100 normal ~30ms traces
# Add outliers
outlier1 = Trace(trace_id="outlier1", spans=[
Span("user-svc", "getUser", 50),
Span("db-svc", "query", 2000, tags={'db.query': 'SELECT * FROM users', 'error': False}) # Slow DB
])
outlier2 = Trace(trace_id="outlier2", spans=[
Span("user-svc", "getUser", 10),
Span("ext-svc", "http.request", 1500, tags={'http.status_code': 500}) # External error
])
traces.extend([outlier1, outlier2])
finder = P99OutlierRootCauseFinder()
finder.fit(traces)
print("P99 Latency:", finder.p99_latency)
causes1 = finder.find_root_causes(outlier1)
print("\nRoot Causes for outlier1:")
for c in causes1:
print(f" {c['span_type']}: score={c['score']:.2f}, dur={c['duration_ms']}ms ({c['contrib_pct']:.0f}%), "
f"reasons={'; '.join(c['reasons'])}")
# Expected: db-svc:query high score due to contrib, slow op, >baseline
if __name__ == "__main__":
demo()
This nails P99 outliers surgically—longest span often lies, but correlations reveal systemic issues. Questions? 🚀