rcaground 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. rcaground/__init__.py +14 -0
  2. rcaground/agents/__init__.py +0 -0
  3. rcaground/agents/evidence.py +322 -0
  4. rcaground/agents/rca.py +333 -0
  5. rcaground/audit/__init__.py +0 -0
  6. rcaground/audit/ledger.py +129 -0
  7. rcaground/audit/manifest.py +170 -0
  8. rcaground/bench/__init__.py +3 -0
  9. rcaground/bench/baselines/__init__.py +23 -0
  10. rcaground/bench/baselines/openrca_agent.py +288 -0
  11. rcaground/bench/baselines/rcaeval_baseline.py +134 -0
  12. rcaground/bench/baselines/rules.py +65 -0
  13. rcaground/bench/baselines/single_prompt_llm.py +122 -0
  14. rcaground/bench/build_rating_harness.py +123 -0
  15. rcaground/bench/configs/re1_ob_smoke.yaml +14 -0
  16. rcaground/bench/configs/re2_ob_smoke.yaml +14 -0
  17. rcaground/bench/dependency.py +50 -0
  18. rcaground/bench/faithfulness.py +463 -0
  19. rcaground/bench/metrics.py +251 -0
  20. rcaground/bench/run_benchmark.py +254 -0
  21. rcaground/bench/run_faithfulness_study.py +318 -0
  22. rcaground/classifier/__init__.py +0 -0
  23. rcaground/classifier/taxonomy.py +59 -0
  24. rcaground/data/alert_rules.yaml +104 -0
  25. rcaground/data/taxonomy.yaml +72 -0
  26. rcaground/graph/__init__.py +0 -0
  27. rcaground/graph/builder.py +150 -0
  28. rcaground/graph/evidence.py +58 -0
  29. rcaground/llm/__init__.py +0 -0
  30. rcaground/llm/client.py +309 -0
  31. rcaground/llm/providers.py +42 -0
  32. rcaground/signals/__init__.py +4 -0
  33. rcaground/signals/alert_synth.py +457 -0
  34. rcaground/signals/log_template.py +51 -0
  35. rcaground/signals/openrca.py +639 -0
  36. rcaground/signals/rcaeval.py +328 -0
  37. rcaground/signals/types.py +121 -0
  38. rcaground-0.1.0.dist-info/METADATA +136 -0
  39. rcaground-0.1.0.dist-info/RECORD +41 -0
  40. rcaground-0.1.0.dist-info/WHEEL +4 -0
  41. rcaground-0.1.0.dist-info/licenses/LICENSE +201 -0
rcaground/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """rcaground: reproducible evaluation of evidence grounding in LLM root cause analysis.
2
+
3
+ Subpackages:
4
+ rcaground.signals adapters that normalise public RCA benchmarks (RCAEval,
5
+ OpenRCA) into one FailureCase schema, plus alert synthesis
6
+ rcaground.graph service dependency graphs from traces or static topology
7
+ rcaground.agents evidence ranking and the reference RCA generator
8
+ rcaground.bench benchmark harness, baselines, and the two-stage
9
+ faithfulness checker
10
+ rcaground.audit run manifests and cost/timing ledger
11
+ rcaground.llm provider-agnostic chat client
12
+ """
13
+
14
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,322 @@
1
+ """
2
+ rcaground/agents/evidence.py — Evidence ranking and selection for incident RCA.
3
+
4
+ Ranks anomalous KPIs, error spans, and log templates by signal strength,
5
+ walks the service dependency graph to boost candidates on the critical
6
+ path, and returns a ranked evidence pack with stable IDs and descriptions.
7
+
8
+ Each evidence item carries a stable ID (kpi:svc:metric, span:traceid,
9
+ logtpl:hash) and a one-line description. The pack is capped at 40 items
10
+ and records its approximate token size.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from collections import Counter, defaultdict
17
+ from dataclasses import dataclass, replace
18
+ from typing import Optional
19
+
20
+ import networkx as nx
21
+ import numpy as np
22
+
23
+ from rcaground.signals.alert_synth import Alert
24
+ from rcaground.signals.types import FailureCase, Span
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class EvidenceItem:
29
+ """A single piece of evidence with stable ID and description."""
30
+
31
+ id: str # Format: kpi:svc:metric | span:traceid | logtpl:hash
32
+ type: str # "kpi", "span", "log"
33
+ score: float # Signal strength; unbounded for KPIs (log1p of |z|), [0,1] for spans/logs
34
+ description: str # One-line description for humans
35
+ service: Optional[str] = None # Service this evidence implicates
36
+ z_score: Optional[float] = None # Raw robust z-score (KPIs only); secondary sort key
37
+ graph_distance: Optional[int] = None # Hops from the alert's service (None = unknown/unreachable)
38
+
39
+
40
+ def _sort_key(item: EvidenceItem) -> tuple[float, float, float]:
41
+ """Deterministic ranking key: score desc, then |z| desc, then graph distance asc.
42
+
43
+ Never falls back to list/insertion order for items that carry any
44
+ distinguishing signal — a KPI's score is a strictly monotone function
45
+ of |z|, so two KPIs with different z can never tie on the first key.
46
+ """
47
+ z_mag = abs(item.z_score) if item.z_score is not None else 0.0
48
+ dist = float(item.graph_distance) if item.graph_distance is not None else math.inf
49
+ return (-item.score, -z_mag, dist)
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class EvidencePack:
54
+ """Ranked evidence for root cause analysis."""
55
+
56
+ case_id: str
57
+ items: list[EvidenceItem] # Sorted by score descending, capped at 40
58
+ token_estimate: int # Approximate token count for LLM consumption
59
+
60
+
61
+ _MAD_TO_STD = 1.4826 # scales MAD to a consistent estimator of stddev for normal data
62
+ _MAD_ABSOLUTE_FLOOR = 1e-9 # final fallback when the pre-window is genuinely all-zero
63
+ _MAD_RELATIVE_FLOOR = 0.01 # minimum scaled-MAD as a fraction of the pre-window's value scale
64
+
65
+
66
+ class RobustScaler:
67
+ """Robust z-score using median and MAD (median absolute deviation)."""
68
+
69
+ @staticmethod
70
+ def robust_z_score(values: list[float], target: float) -> float:
71
+ """Compute robust z-score: (target - median) / scaled_MAD.
72
+
73
+ The MAD floor is relative to the pre-window's own value SCALE
74
+ (``_MAD_RELATIVE_FLOOR * max(|median|, max|v|)``), not a fixed
75
+ absolute epsilon — ported from ``rcaground/signals/alert_synth.py``'s
76
+ ``_robust_z_scores``. A near-constant-but-not-flat pre-window (MAD
77
+ rounds to 0.0 in float while the metric still moves a little) would
78
+ otherwise divide a tiny fluctuation by ~1e-9 and report a z-score
79
+ in the millions.
80
+ """
81
+ if len(values) < 2:
82
+ return 0.0
83
+
84
+ values_arr = np.array(values, dtype=np.float64)
85
+ median = np.median(values_arr)
86
+ mad = np.median(np.abs(values_arr - median))
87
+
88
+ scale_reference = max(abs(median), float(np.max(np.abs(values_arr))))
89
+ scaled_mad = max(
90
+ mad * _MAD_TO_STD,
91
+ _MAD_RELATIVE_FLOOR * scale_reference,
92
+ _MAD_ABSOLUTE_FLOOR,
93
+ )
94
+ return (target - median) / scaled_mad
95
+
96
+
97
+ class EvidenceRanker:
98
+ """Rank evidence items from a failure case."""
99
+
100
+ def __init__(self, case: FailureCase, alert: Alert):
101
+ self.case = case
102
+ self.alert = alert
103
+ self.items: list[EvidenceItem] = []
104
+
105
+ # Split metrics by baseline boundary
106
+ self.baseline_boundary = self._compute_baseline_boundary()
107
+ self.pre_times, self.post_times = self._split_times()
108
+
109
+ def _compute_baseline_boundary(self) -> int:
110
+ """Find the temporal midpoint (split between pre and post baseline)."""
111
+ all_times = []
112
+ for series in self.case.metrics.values():
113
+ all_times.extend(series.times)
114
+
115
+ if not all_times:
116
+ return 0
117
+ return all_times[len(all_times) // 2]
118
+
119
+ def _split_times(self) -> tuple[list[int], list[int]]:
120
+ """Split times into pre-baseline and post-baseline."""
121
+ all_times = []
122
+ for series in self.case.metrics.values():
123
+ all_times.extend(series.times)
124
+
125
+ if not all_times:
126
+ return [], []
127
+
128
+ boundary = self.baseline_boundary
129
+ pre = sorted(set(t for t in all_times if t < boundary))
130
+ post = sorted(set(t for t in all_times if t >= boundary))
131
+ return pre, post
132
+
133
+ def rank_kpis(self) -> list[EvidenceItem]:
134
+ """Rank KPIs by robust z-score anomaly."""
135
+ items = []
136
+
137
+ for key, series in self.case.metrics.items():
138
+ if not series.values or len(series.values) < 2:
139
+ continue
140
+
141
+ # Split by baseline
142
+ values_array = np.array(series.values, dtype=np.float64)
143
+ times_array = np.array(series.times, dtype=np.int64)
144
+
145
+ pre_mask = times_array < self.baseline_boundary
146
+ post_mask = times_array >= self.baseline_boundary
147
+
148
+ if pre_mask.sum() < 2 or post_mask.sum() < 1:
149
+ continue
150
+
151
+ pre_values = values_array[pre_mask].tolist()
152
+ post_values = values_array[post_mask].tolist()
153
+
154
+ # Maximum post-breach value
155
+ max_post = max(post_values) if post_values else 0.0
156
+
157
+ # Robust z-score against pre-baseline. Score is log1p(|z|):
158
+ # unbounded and strictly monotone in |z|, so a z=6000 metric
159
+ # always outranks a z=4 one instead of both clipping to 1.0
160
+ # and being ordered by incidental CSV column order.
161
+ z_score = RobustScaler.robust_z_score(pre_values, max_post)
162
+
163
+ if abs(z_score) > 0.3: # Filter weak signals
164
+ svc, metric = key.split(":")
165
+ item = EvidenceItem(
166
+ id=f"kpi:{svc}:{metric}",
167
+ type="kpi",
168
+ score=math.log1p(abs(z_score)),
169
+ description=f"{key} spiked to {max_post:.1f} (z={z_score:.1f})",
170
+ service=svc,
171
+ z_score=z_score,
172
+ )
173
+ items.append(item)
174
+
175
+ return sorted(items, key=_sort_key)
176
+
177
+ def rank_spans(self) -> list[EvidenceItem]:
178
+ """Rank spans by error-ratio change."""
179
+ items = []
180
+
181
+ if not self.case.traces:
182
+ return items
183
+
184
+ # Group spans by (parent_service, child_service) edge
185
+ edges: dict[tuple[str, str], list[Span]] = defaultdict(list)
186
+ by_id = {s.span_id: s for s in self.case.traces}
187
+
188
+ for span in self.case.traces:
189
+ if span.parent_span_id and span.parent_span_id in by_id:
190
+ parent = by_id[span.parent_span_id]
191
+ if parent.service != span.service:
192
+ edges[(parent.service, span.service)].append(span)
193
+
194
+ # Compute error-ratio change for each edge
195
+ for (caller, callee), spans in edges.items():
196
+ if len(spans) < 2:
197
+ continue
198
+
199
+ # Split by baseline (baseline_boundary is in seconds, start_time_ms is in milliseconds)
200
+ baseline_ms = self.baseline_boundary * 1000 if self.baseline_boundary > 0 else float('inf')
201
+ pre_spans = [s for s in spans if s.start_time_ms < baseline_ms]
202
+ post_spans = [s for s in spans if s.start_time_ms >= baseline_ms]
203
+
204
+ if not pre_spans or not post_spans:
205
+ continue
206
+
207
+ pre_error_ratio = sum(
208
+ 1 for s in pre_spans if s.status_code and s.status_code >= 400
209
+ ) / len(pre_spans)
210
+ post_error_ratio = sum(
211
+ 1 for s in post_spans if s.status_code and s.status_code >= 400
212
+ ) / len(post_spans)
213
+
214
+ error_change = post_error_ratio - pre_error_ratio
215
+ if error_change > 0.1: # Significant error increase
216
+ trace_id = post_spans[0].trace_id
217
+ item = EvidenceItem(
218
+ id=f"span:{trace_id}",
219
+ type="span",
220
+ score=min(1.0, error_change),
221
+ description=f"{caller}→{callee} errors {pre_error_ratio:.0%}→{post_error_ratio:.0%}",
222
+ service=callee,
223
+ )
224
+ items.append(item)
225
+
226
+ return sorted(items, key=_sort_key)
227
+
228
+ def rank_logs(self) -> list[EvidenceItem]:
229
+ """Rank log templates by novelty (post-window only)."""
230
+ items = []
231
+
232
+ if not self.case.logs:
233
+ return items
234
+
235
+ # Split logs by baseline
236
+ pre_templates = Counter(
237
+ l.template_hash for l in self.case.logs if l.time < self.baseline_boundary
238
+ )
239
+ post_templates = Counter(
240
+ l.template_hash for l in self.case.logs if l.time >= self.baseline_boundary
241
+ )
242
+
243
+ # Novelty score: appears post but not pre (or mostly post)
244
+ for logtpl_hash, post_count in post_templates.items():
245
+ pre_count = pre_templates.get(logtpl_hash, 0)
246
+ novelty = post_count / (pre_count + post_count) if (pre_count + post_count) > 0 else 1.0
247
+
248
+ if novelty > 0.5: # Favor templates with post-window dominance
249
+ # Find the log event for context
250
+ log_event = next(
251
+ (l for l in self.case.logs if l.template_hash == logtpl_hash),
252
+ None,
253
+ )
254
+
255
+ item = EvidenceItem(
256
+ id=f"logtpl:{logtpl_hash}",
257
+ type="log",
258
+ score=novelty,
259
+ description=f"{log_event.service}: {log_event.template[:60]}" if log_event else logtpl_hash,
260
+ service=log_event.service if log_event else None,
261
+ )
262
+ items.append(item)
263
+
264
+ return sorted(items, key=_sort_key)
265
+
266
+ def _distances_from_alert(self) -> dict[str, int]:
267
+ """Undirected hop count from the alert's service to every reachable
268
+ service. Empty when there is no topology or no alert service."""
269
+ topo = self.case.topology
270
+ alerting_svc = self.alert.service
271
+ if not alerting_svc or topo is None or topo.number_of_nodes() == 0:
272
+ return {}
273
+ undirected = topo.to_undirected()
274
+ if alerting_svc not in undirected:
275
+ return {}
276
+ return nx.single_source_shortest_path_length(undirected, alerting_svc)
277
+
278
+ def boost_graph_path(self, items: list[EvidenceItem]) -> list[EvidenceItem]:
279
+ """Attach graph distance to every item, boost items within 2 hops of
280
+ the alert's service by 10%, and return the pack in ranked order."""
281
+ distances = self._distances_from_alert()
282
+
283
+ out = []
284
+ for item in items:
285
+ dist = distances.get(item.service) if item.service else None
286
+ score = item.score * 1.1 if (dist is not None and dist <= 2) else item.score
287
+ out.append(replace(item, score=score, graph_distance=dist))
288
+
289
+ return sorted(out, key=_sort_key)
290
+
291
+ def rank(self) -> EvidencePack:
292
+ """Rank all evidence and return a capped pack."""
293
+ # Rank all evidence types
294
+ kpi_items = self.rank_kpis()
295
+ span_items = self.rank_spans()
296
+ log_items = self.rank_logs()
297
+
298
+ # Merge and deduplicate
299
+ all_items = kpi_items + span_items + log_items
300
+ seen_ids = set()
301
+ deduped = []
302
+ for item in all_items:
303
+ if item.id not in seen_ids:
304
+ deduped.append(item)
305
+ seen_ids.add(item.id)
306
+
307
+ # Boost items on critical path
308
+ boosted = self.boost_graph_path(deduped)
309
+
310
+ # Cap at 40 items
311
+ capped = boosted[:40]
312
+
313
+ # Estimate token count (rough: ~4 tokens per word, 60 chars per item description)
314
+ token_estimate = sum(
315
+ len(item.description.split()) for item in capped
316
+ ) * 2 # Conservative estimate
317
+
318
+ return EvidencePack(
319
+ case_id=self.case.case_id,
320
+ items=capped,
321
+ token_estimate=token_estimate,
322
+ )
@@ -0,0 +1,333 @@
1
+ """
2
+ rcaground/agents/rca.py — RCA agent producing structured RCAResult with validated claims.
3
+
4
+ Every claim is grounded in evidence IDs that were actually shown to the model,
5
+ and a claim whose text names a service none of its cited evidence belongs to is
6
+ dropped (see `_claim_drop_reason`). The headline `root_cause_service` is then
7
+ verified against the surviving claims — an unverified headline is reported as
8
+ "needs_review", never as a specific service.
9
+
10
+ Schema enforced with Pydantic for type safety and validation.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+ from typing import Optional
18
+
19
+ from pydantic import BaseModel, Field, ValidationError, field_validator
20
+
21
+ from rcaground.agents.evidence import EvidencePack
22
+ from rcaground.llm.client import LLMClient
23
+
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # Pydantic schemas
27
+ # ---------------------------------------------------------------------------
28
+
29
+ class Claim(BaseModel):
30
+ """A single RCA claim with supporting evidence."""
31
+
32
+ text: str # The claim itself
33
+ evidence_ids: list[str] = Field(min_length=1) # At least one evidence ID
34
+ confidence: float = Field(ge=0.0, le=1.0) # Confidence in [0, 1]
35
+ # (source_service, target_service): the claim says a fault propagated source -> target
36
+ causal_edges: list[tuple[str, str]] = Field(default_factory=list)
37
+
38
+ @field_validator("evidence_ids")
39
+ def validate_evidence_ids(cls, v):
40
+ """Validate that evidence IDs are non-empty."""
41
+ if not v:
42
+ raise ValueError("evidence_ids must contain at least one ID")
43
+ return v
44
+
45
+
46
+ class RCAResult(BaseModel):
47
+ """Root Cause Analysis result with validated claims.
48
+
49
+ `root_cause_service` is the VERIFIED root cause: it equals
50
+ `proposed_root_cause_service` (the model's own summary line) only when a
51
+ surviving, validated claim cites evidence belonging to that service.
52
+ Otherwise it is "needs_review" (or "unknown" when the model abstained) and
53
+ `review_reason` explains why — the headline is never presented as a fact
54
+ the per-claim validation does not also support.
55
+ """
56
+
57
+ case_id: str
58
+ root_cause_service: str
59
+ probable_cause: str
60
+ contributing_factors: list[str] = Field(default_factory=list)
61
+ claims: list[Claim] = Field(default_factory=list)
62
+ dropped_claims: int = 0 # Number of claims dropped in validation
63
+ drop_reasons: list[str] = Field(default_factory=list) # one string per dropped claim
64
+ proposed_root_cause_service: str = "" # the model's raw summary value (audit trail)
65
+ root_cause_verified: bool = False
66
+ review_reason: str = ""
67
+
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # RCA Agent
71
+ # ---------------------------------------------------------------------------
72
+
73
+ _RCA_SYSTEM = (
74
+ "You are a site-reliability incident analyst. You are given a monitoring "
75
+ "alert and a ranked list of evidence items, each with a stable ID. Produce "
76
+ "a root-cause analysis whose every claim cites one or more of those exact "
77
+ "evidence IDs. Never invent an ID. Never cite an ID that is not in the list."
78
+ )
79
+
80
+ _RCA_PROMPT = """CASE: {case_id}
81
+ ALERT: {alert}
82
+
83
+ EVIDENCE (ranked; cite these IDs verbatim):
84
+ {evidence}
85
+
86
+ Reply with ONLY a JSON object:
87
+ {{
88
+ "root_cause_service": "<service name>",
89
+ "probable_cause": "<one sentence>",
90
+ "contributing_factors": ["<factor>", ...],
91
+ "claims": [
92
+ {{"text": "<claim>", "evidence_ids": ["<id from the list>", ...], "confidence": <0.0-1.0>}}
93
+ ]
94
+ }}
95
+ Produce 3-6 claims. Each claim's evidence_ids must be a non-empty subset of the IDs above."""
96
+
97
+ _RCA_PROMPT_EDGES = """CASE: {case_id}
98
+ ALERT: {alert}
99
+
100
+ EVIDENCE (ranked; cite these IDs verbatim):
101
+ {evidence}
102
+
103
+ Reply with ONLY a JSON object:
104
+ {{
105
+ "root_cause_service": "<service name>",
106
+ "probable_cause": "<one sentence>",
107
+ "contributing_factors": ["<factor>", ...],
108
+ "claims": [
109
+ {{"text": "<claim>", "evidence_ids": ["<id from the list>", ...], "confidence": <0.0-1.0>,
110
+ "causal_edges": [["<source service>", "<target service>"], ...]}}
111
+ ]
112
+ }}
113
+ Produce 3-6 claims. Each claim's evidence_ids must be a non-empty subset of the IDs above.
114
+ causal_edges lists each fault propagation the claim asserts, as [source, target] service pairs meaning the fault spread from source to target; use [] if the claim asserts none."""
115
+
116
+
117
+ def _parse_edges(raw) -> list[tuple[str, str]]:
118
+ """Keep only well-formed [source, target] string pairs; drop the rest."""
119
+ if not isinstance(raw, list):
120
+ return []
121
+ return [
122
+ (e[0], e[1]) for e in raw
123
+ if isinstance(e, (list, tuple)) and len(e) == 2 and all(isinstance(x, str) and x for x in e)
124
+ ]
125
+
126
+
127
+ def _extract_json_object(text: str) -> dict:
128
+ """Parse the first {...} object out of an LLM reply, tolerating code fences."""
129
+ m = re.search(r"\{.*\}", text, re.DOTALL)
130
+ if not m:
131
+ raise ValueError(f"no JSON object in LLM reply: {text[:200]!r}")
132
+ return json.loads(m.group(0))
133
+
134
+
135
+ # Service names shorter than this are excluded from the claim-text scan to
136
+ # avoid matching common English words ("main", "redis" are pseudo-services in
137
+ # the RCAEval Online-Boutique data). Real service names are longer
138
+ # ("currencyservice", "checkoutservice", "frontend", ...).
139
+ _MIN_SERVICE_NAME_LEN = 6
140
+
141
+
142
+ def _service_of(eid: str) -> Optional[str]:
143
+ """Service named by a KPI evidence id: "kpi:checkoutservice:latency-50" ->
144
+ "checkoutservice". None for span:/logtpl:/cluster ids with no owning service."""
145
+ parts = eid.split(":")
146
+ if len(parts) >= 3 and parts[0] == "kpi" and parts[1] != "cluster":
147
+ return parts[1]
148
+ return None
149
+
150
+
151
+ class RCAAgent:
152
+ """Generates RCA with evidence-grounded claims."""
153
+
154
+ def __init__(self, evidence_pack: EvidencePack, request_edges: bool = False):
155
+ self.evidence_pack = evidence_pack
156
+ self.request_edges = request_edges
157
+ self.valid_evidence_ids = {item.id for item in evidence_pack.items}
158
+ self.pack_services = {
159
+ it.service for it in evidence_pack.items
160
+ if it.service and len(it.service) >= _MIN_SERVICE_NAME_LEN
161
+ }
162
+
163
+ def generate(
164
+ self,
165
+ alert_text: str,
166
+ llm_client: LLMClient,
167
+ model_digest: str = "ollama:llama3.1",
168
+ top_k: int = 12,
169
+ seed: int = 0,
170
+ max_tokens: int = 900,
171
+ ) -> RCAResult:
172
+ """Prompt an LLM with the top-k evidence items and parse an RCAResult.
173
+
174
+ The RCA model family should differ from the faithfulness chat-judge's
175
+ (see rcaground/bench/faithfulness.py). Claims that fail Pydantic validation are
176
+ skipped; claims are then validated against the evidence IDs ACTUALLY
177
+ SHOWN in the prompt (items[:top_k]) — not the full pack — and against
178
+ evidence-service consistency (see `_claim_drop_reason`).
179
+ """
180
+ items = self.evidence_pack.items[:top_k]
181
+ shown_ids = {it.id for it in items}
182
+ rendered = "\n".join(
183
+ f"- {it.id} (score {it.score:.2f}, {it.service}): {it.description}" for it in items
184
+ )
185
+ prompt = (_RCA_PROMPT_EDGES if self.request_edges else _RCA_PROMPT).format(
186
+ case_id=self.evidence_pack.case_id,
187
+ alert=alert_text or "[silent alert]",
188
+ evidence=rendered,
189
+ )
190
+ resp = llm_client.call(
191
+ prompt=prompt,
192
+ model_digest=model_digest,
193
+ system_prompt=_RCA_SYSTEM,
194
+ max_tokens=max_tokens,
195
+ seed=seed,
196
+ )
197
+ if resp.truncated and not resp.text.strip():
198
+ # A reasoning-model generator (e.g. a "thinking" family) can burn the
199
+ # entire budget on hidden <think> content before any JSON is emitted.
200
+ # One retry at 3x the budget, same pattern as the chat judge's retry
201
+ # (rcaground/bench/faithfulness.py CHAT_JUDGE_RETRY_MAX_TOKENS).
202
+ resp = llm_client.call(
203
+ prompt=prompt, model_digest=model_digest, system_prompt=_RCA_SYSTEM,
204
+ max_tokens=max_tokens * 3, seed=seed,
205
+ )
206
+ parsed = _extract_json_object(resp.text)
207
+
208
+ claims: list[Claim] = []
209
+ for raw in parsed.get("claims", []):
210
+ try:
211
+ claims.append(
212
+ Claim(
213
+ text=str(raw["text"]),
214
+ evidence_ids=list(raw["evidence_ids"]),
215
+ confidence=float(raw.get("confidence", 0.5)),
216
+ causal_edges=_parse_edges(raw.get("causal_edges", [])),
217
+ )
218
+ )
219
+ except (KeyError, TypeError, ValueError, ValidationError):
220
+ continue
221
+
222
+ return self.create_result(
223
+ root_cause_service=str(parsed.get("root_cause_service", "unknown")),
224
+ probable_cause=str(parsed.get("probable_cause", "")),
225
+ claims=claims,
226
+ contributing_factors=[str(f) for f in parsed.get("contributing_factors", [])],
227
+ allowed_ids=shown_ids,
228
+ )
229
+
230
+ def _claim_drop_reason(self, claim: Claim, allowed_ids: set[str]) -> Optional[str]:
231
+ """Return why a claim should be dropped, or None if it is acceptable.
232
+
233
+ 1. Every cited id must be in `allowed_ids` (for `generate`, the subset
234
+ rendered in the prompt; otherwise the whole pack).
235
+ 2. Evidence-service consistency: if the claim's text names a known
236
+ service that none of its cited KPI ids belong to, the claim is
237
+ attributing evidence to the wrong service.
238
+ """
239
+ outside = [e for e in claim.evidence_ids if e not in allowed_ids]
240
+ if outside:
241
+ return f"cites evidence not shown in the prompt: {outside}"
242
+
243
+ cited_services = {s for e in claim.evidence_ids if (s := _service_of(e))}
244
+ named = {
245
+ s for s in self.pack_services
246
+ if re.search(rf"\b{re.escape(s)}\b", claim.text, re.IGNORECASE)
247
+ }
248
+ if named and not (named & cited_services):
249
+ return (
250
+ f"names service(s) {sorted(named)} but cites evidence only for "
251
+ f"{sorted(cited_services) or ['(no service)']}"
252
+ )
253
+ return None
254
+
255
+ def _validate(
256
+ self, claims: list[Claim], allowed_ids: set[str]
257
+ ) -> tuple[list[Claim], list[str]]:
258
+ valid, reasons = [], []
259
+ for claim in claims:
260
+ reason = self._claim_drop_reason(claim, allowed_ids)
261
+ if reason is None:
262
+ valid.append(claim)
263
+ else:
264
+ reasons.append(f"{claim.text[:70]!r}: {reason}")
265
+ return valid, reasons
266
+
267
+ def validate_and_filter_claims(self, claims: list[Claim]) -> tuple[list[Claim], int]:
268
+ """Back-compat wrapper: validate against the full pack, return a count."""
269
+ valid, reasons = self._validate(claims, self.valid_evidence_ids)
270
+ return valid, len(reasons)
271
+
272
+ def _resolve_root_cause(
273
+ self, proposed: str, valid_claims: list[Claim]
274
+ ) -> tuple[str, bool, str]:
275
+ """Only present `proposed` as THE root cause if a surviving claim cites
276
+ evidence for it; otherwise "needs_review" / "unknown"."""
277
+ proposed = (proposed or "").strip()
278
+ backed = {s for c in valid_claims for e in c.evidence_ids if (s := _service_of(e))}
279
+ if proposed.lower() in ("", "unknown", "none", "n/a"):
280
+ return "unknown", False, "the model did not identify a specific root-cause service"
281
+ if proposed in backed:
282
+ return proposed, True, ""
283
+ return "needs_review", False, (
284
+ f"the model named {proposed!r} but no surviving claim cites evidence "
285
+ f"for it (services backed by surviving claims: {sorted(backed) or 'none'})"
286
+ )
287
+
288
+ def create_result(
289
+ self,
290
+ root_cause_service: str,
291
+ probable_cause: str,
292
+ claims: list[Claim],
293
+ contributing_factors: Optional[list[str]] = None,
294
+ allowed_ids: Optional[set[str]] = None,
295
+ ) -> RCAResult:
296
+ """Create an RCAResult, dropping claims that fail validation and
297
+ verifying the headline `root_cause_service` against what survives.
298
+
299
+ `allowed_ids` is the set citations are checked against — the prompt's
300
+ shown subset when called from `generate`, else the whole pack.
301
+ """
302
+ valid_claims, reasons = self._validate(
303
+ claims, allowed_ids if allowed_ids is not None else self.valid_evidence_ids
304
+ )
305
+ resolved, verified, review_reason = self._resolve_root_cause(
306
+ root_cause_service, valid_claims
307
+ )
308
+
309
+ try:
310
+ return RCAResult(
311
+ case_id=self.evidence_pack.case_id,
312
+ root_cause_service=resolved,
313
+ proposed_root_cause_service=(root_cause_service or "").strip(),
314
+ root_cause_verified=verified,
315
+ review_reason=review_reason,
316
+ probable_cause=probable_cause,
317
+ contributing_factors=contributing_factors or [],
318
+ claims=valid_claims,
319
+ dropped_claims=len(reasons),
320
+ drop_reasons=reasons,
321
+ )
322
+ except Exception:
323
+ # If schema validation fails, return empty result
324
+ return RCAResult(
325
+ case_id=self.evidence_pack.case_id,
326
+ root_cause_service="unknown",
327
+ proposed_root_cause_service=(root_cause_service or "").strip(),
328
+ probable_cause="",
329
+ claims=[],
330
+ dropped_claims=len(claims),
331
+ drop_reasons=["RCAResult schema validation failed"],
332
+ review_reason="RCAResult schema validation failed",
333
+ )
File without changes