import networkx as nx
import numpy as np
from scipy.stats import norm, expon
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Tuple
import heapq
import time
# --- Data Models ---
@dataclass
class SpanFragment:
"""
Represents a piece of partial telemetry (e.g., a log line with a timestamp,
or a span missing its parent ID).
"""
id: str
service_name: str
start_time: float # Unix epoch
duration: float # Seconds
tags: Dict[str, str] = field(default_factory=dict)
parent_id: Optional[str] = None # If None, this is an orphan
@property
def end_time(self) -> float:
return self.start_time + self.duration
@dataclass
class ServiceTopology:
"""
Represents historical knowledge of the architecture.
Used to calculate P(j is child of i).
"""
# Map: (ParentService, ChildService) -> Probability
adjacency_priors: Dict[Tuple[str, str], float] = field(default_factory=dict)
# Map: (ParentService, ChildService) -> (MeanLatency, StdDevLatency)
latency_profiles: Dict[Tuple[str, str], Tuple[float, float]] = field(default_factory=dict)
# --- The Inference Engine ---
class TraceSynthesizer:
def __init__(self, topology: ServiceTopology, confidence_threshold: float = 0.75):
self.topology = topology
self.confidence_threshold = confidence_threshold
def synthesize(self, fragments: List[SpanFragment]) -> nx.DiGraph:
"""
Main entry point. Attempts to reconstruct a call graph from a list
of disconnected fragments.
"""
graph = nx.DiGraph()
# 1. Add all fragments as nodes
for frag in fragments:
graph.add_node(frag.id, data=frag)
# 2. Identify explicit links (if any partial context exists)
# (Skipped here for brevity, focusing on the probabilistic engine)
# 3. Identify Orphans (Nodes with no parent)
orphans = [f for f in fragments if f.parent_id is None]
# 4. Generate Candidate Edges
# We only try to link a span to potential parents that finished AFTER the child started.
# Optimization: Sort by time to reduce O(N^2) complexity
candidates = []
# Sort all fragments by start time
sorted_frags = sorted(fragments, key=lambda x: x.start_time)
for child in orphans:
potential_parents = self._find_temporal_candidates(child, sorted_frags)
for parent in potential_parents:
# Calculate Probability of Causality
prob = self._calculate_causality_probability(parent, child)
if prob > self.confidence_threshold:
# Store candidate: (prob, parent_id, child_id)
candidates.append((prob, parent.id, child.id))
# 5. Graph Resolution (Greedy approach)
# Sort candidates by probability descending
candidates.sort(key=lambda x: x[0], reverse=True)
# Link the highest probability edges first, ensuring no node gets two parents
# (unless the engine supports fan-in from different sources, typically we assume 1 direct caller)
linked_children = set()
for prob, p_id, c_id in candidates:
if c_id not in linked_children:
graph.add_edge(p_id, c_id, weight=prob)
linked_children.add(c_id)
# Update the data model to reflect synthesis
# In a real system, we would emit a 'SYNTHESIZED_LINK' telemetry event
return graph
def _find_temporal_candidates(self, child: SpanFragment, all_frags: List[SpanFragment]) -> List[SpanFragment]:
"""
Filter fragments that could logically be the parent based on time.
Parent must start before child (usually) and end after child starts.
"""
candidates = []
for frag in all_frags:
if frag.id == child.id: continue
# Basic Temporal Heuristic:
# Parent starts before Child
# Parent finishes after Child starts (Overlap)
# Note: In async systems, parent might finish before child starts.
# We use a宽松 buffer for async flags.
is_temporal_match = frag.start_time <= child.start_time and frag.end_time >= child.start_time
if is_temporal_match:
candidates.append(frag)
return candidates
def _calculate_causality_probability(self, parent: SpanFragment, child: SpanFragment) -> float:
"""
P(Link | Evidence) = P(Temporal | Link) * P(Topology | Link) * P(Context | Link)
"""
# 1. Topological Prior
# Do we know this connection exists?
topo_key = (parent.service_name, child.service_name)
prior_topo = self.topology.adjacency_priors.get(topo_key, 0.01) # Low prior for unknown links
# 2. Temporal / Latency Probability
# Given the services, does the time gap make sense?
observed_gap = child.start_time - parent.start_time
# If we have latency profile, use Gaussian. If not, use Exponential decay.
if topo_key in self.topology.latency_profiles:
mean, std = self.topology.latency_profiles[topo_key]
# Calculate PDF of normal distribution
p_time = norm.pdf(observed_gap, loc=mean, scale=std)
else:
# Fallback: Assume generic latency distribution, penalize large gaps
p_time = expon.pdf(observed_gap, scale=0.1) # scale=100ms avg
# 3. Contextual Similarity (Log/Tag overlap)
# Simple Jaccard Index on tags keys/values
p_context = self._calculate_tag_similarity(parent.tags, child.tags)
# Combine (Naive Bayes approach)
# We scale the result to be roughly 0.0 to 1.0
# We heavily weight the Topology because time overlaps can be coincidental.
score = (prior_topo * 10) * p_time * (1 + p_context)
# Normalize / Cap
return min(score, 1.0)
def _calculate_tag_similarity(self, tags_a: Dict, tags_b: Dict) -> float:
# Check for explicit linkages like HTTP paths matching, or IDs in logs
# This is a placeholder for more complex semantic similarity
if not tags_a or not tags_b: return 0.0
# Example: If HTTP route matches
if tags_a.get("http.route") and tags_a.get("http.route") == tags_b.get("http.route"):
return 0.5
return 0.0
# --- Simulation ---
def run_simulation():
print("--- Initializing Trace Synthesis Engine ---")
# 1. Define Topology Knowledge (Priors)
topology = ServiceTopology()
# Service A calls Service B with 95% probability
topology.adjacency_priors[("service-a", "service-b")] = 0.95
# Latency between A and B is Normal(20ms, 5ms)
topology.latency_profiles[("service-a", "service-b")] = (0.02, 0.005)
topology.adjacency_priors[("service-b", "service-db")] = 0.90
topology.latency_profiles[("service-b", "service-db")] = (0.005, 0.001)
engine = TraceSynthesizer(topology, confidence_threshold=0.5)
# 2. Simulate Partial Telemetry
# Scenario: Request hits Service A -> Service B -> Service DB
# Context propagation broke between B and DB. DB span is an orphan.
t0 = time.time()
fragments = [
# Root Span (Service A)
SpanFragment(
id="span-a",
service_name="service-a",
start_time=t0,
duration=0.05,
tags={"http.route": "/api/v1/item"}
),
# Child Span (Service B) - Has parent A (simulated correctly)
SpanFragment(
id="span-b",
service_name="service-b",
start_time=t0 + 0.021, # 21ms later
duration=0.025,
parent_id="span-a",
tags={"http.route": "/api/v1/item"}
),
# Orphan Span (Service DB) - Context Lost!
SpanFragment(
id="span-db",
service_name="service-db",
start_time=t0 + 0.025, # Inside B's window
duration=0.010,
parent_id=None, # The problem!
tags={"db.system": "postgres"}
)
]
print(f"Input: {len(fragments)} fragments. Orphans: {len([f for f in fragments if not f.parent_id])}")
# 3. Run Synthesis
reconstructed_graph = engine.synthesize(fragments)
# 4. Output Results
print("\n--- Reconstructed Graph Edges ---")
for u, v, data in reconstructed_graph.edges(data=True):
p_node = next(f for f in fragments if f.id == u)
c_node = next(f for f in fragments if f.id == v)
print(f"Link: {p_node.service_name} ({u[:6]}) -> {c_node.service_name} ({v[:6]}) | Confidence: {data['weight']:.4f}")
# Verification
assert reconstructed_graph.has_edge("span-b", "span-db"), "Failed to link DB to B!"
print("\nSUCCESS: Trace graph reconstructed successfully.")
if __name__ == "__main__":
run_simulation()