Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile +1 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml +21 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py +1005 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json +24 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json +210 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py +298 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh +28 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py +1005 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json +14 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json +210 -0
- tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh +19 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile +1 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml +21 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py +1005 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubric.json +24 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.py +298 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.sh +28 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py +1005 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/expected.json +9 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/test.sh +19 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile +1 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml +21 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py +1005 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json +24 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py +298 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh +28 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py +1005 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json +9 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh +19 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile +1 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml +21 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py +1005 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json +24 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py +298 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh +28 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py +1005 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json +9 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json +24 -0
- tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh +19 -0
- tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile +1 -0
- tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml +21 -0
- tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py +1005 -0
- tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json +24 -0
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
FROM ag2435/sre-otel-snapshot:{code_tag}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
build:
|
| 4 |
+
context: ${CONTEXT_DIR}
|
| 5 |
+
pull: true
|
| 6 |
+
image: ${MAIN_IMAGE_NAME}
|
| 7 |
+
command: [ "sh", "-c", "sleep infinity" ]
|
| 8 |
+
privileged: true
|
| 9 |
+
environment:
|
| 10 |
+
- TEST_DIR=${TEST_DIR}
|
| 11 |
+
- CONTEXT_DIR=${CONTEXT_DIR}
|
| 12 |
+
volumes:
|
| 13 |
+
- /var/run/docker.sock:/var/run/docker.sock
|
| 14 |
+
- ${CONTEXT_DIR}:${CONTEXT_DIR}
|
| 15 |
+
- ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH}
|
| 16 |
+
- ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH}
|
| 17 |
+
deploy:
|
| 18 |
+
resources:
|
| 19 |
+
limits:
|
| 20 |
+
cpus: ${CPUS}
|
| 21 |
+
memory: ${MEMORY}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T16:32:19.033653+00:00",
|
| 3 |
+
"feature_flag": "adFailure",
|
| 4 |
+
"description": "A feature flag in the ad service's `GetAds` handler threw `StatusRuntimeException(Status.UNAVAILABLE)` on ~10% of calls (`random.nextInt(10) == 0`); the frontend `/api/data` route caught the gRPC error and returned HTTP 500, but React Query's default `adList = []` fallback masked the failure in the UI — the yellow ad banner silently rendered blank rather than showing an error.",
|
| 5 |
+
"mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205): on every `getAds` gRPC call, after ads have been collected and the request/response type attributes set, the service evaluates `ffClient.getBooleanValue(\"adFailure\", false, evaluationContext)`. When `true`, it throws `StatusRuntimeException(Status.UNAVAILABLE)` with probability 1/10 (`random.nextInt(10) == 0`) at [`AdService.java#L206`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L206).\n\nThe exception is caught at [`AdService.java#L218`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L218): the catch block adds an \"Error\" span event (line 219-220), sets the span status to ERROR (line 221), logs a WARN \"GetAds Failed with status {UNAVAILABLE}\" (line 222), and calls `responseObserver.onError(e)` (line 223) which sends the gRPC UNAVAILABLE status back to the caller.\n\nThe frontend calls the ad service via [`Ad.gateway.ts#L14`](../../opentelemetry-demo/src/frontend/gateways/rpc/Ad.gateway.ts#L14) (`client.getAds`), invoked from the `/api/data` route at [`data.ts#L15`](../../opentelemetry-demo/src/frontend/pages/api/data.ts#L15). When the gRPC call fails, the error propagates through the Next.js API route as an unhandled rejection, and the frontend-proxy Envoy returns HTTP 500 to the client.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [
|
| 8 |
+
{
|
| 9 |
+
"metric_family": "rpc_server_duration_milliseconds",
|
| 10 |
+
"signal_layer": "root_cause",
|
| 11 |
+
"defining_labels": {
|
| 12 |
+
"rpc_grpc_status_code": "14",
|
| 13 |
+
"rpc_method": "GetAds",
|
| 14 |
+
"rpc_service": "oteldemo.AdService",
|
| 15 |
+
"service_name": "ad"
|
| 16 |
+
},
|
| 17 |
+
"variants": [
|
| 18 |
+
{
|
| 19 |
+
"type": "created (fixed after human verification)",
|
| 20 |
+
"query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])",
|
| 21 |
+
"description": "gRPC server call count for AdService/GetAds with status code 14 (UNAVAILABLE). This new series appeared because the adFailure flag causes AdService.java to throw StatusRuntimeException(Status.UNAVAILABLE) with 1/10 probability on each GetAds call.",
|
| 22 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 23 |
+
"onset_offset_seconds": 520,
|
| 24 |
+
"onset_reasoning": "The metric type is 'created'. Pre-incident baseline is 0. At 16:41:00 UTC the rate first rises above zero (0.0048), approximately 9 minutes after the incident time. This is the first appearance of rpc_grpc_status_code=14 (UNAVAILABLE) errors for the AdService, indicating the onset of the fault."
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"type": "created (fixed after human verification)",
|
| 28 |
+
"query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])",
|
| 29 |
+
"description": "Cumulative gRPC server call duration (ms) for AdService/GetAds UNAVAILABLE errors. Tracks the total latency of the failed GetAds RPCs triggered by the adFailure flag.",
|
| 30 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 31 |
+
"onset_offset_seconds": 520,
|
| 32 |
+
"onset_reasoning": "The metric type is 'created'. Pre-incident baseline is 0. At 16:41:00 UTC the value first rises to 0.0145643, which is the first non-zero reading after the incident time (16:32:19 UTC), indicating the onset of rpc_server_duration for status_code=14 (UNAVAILABLE) errors on AdService.GetAds."
|
| 33 |
+
}
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"metric_family": "traces_span_metrics_calls",
|
| 38 |
+
"signal_layer": "root_cause",
|
| 39 |
+
"defining_labels": {
|
| 40 |
+
"service_name": "ad",
|
| 41 |
+
"span_kind": "SPAN_KIND_SERVER",
|
| 42 |
+
"span_name": "oteldemo.AdService/GetAds",
|
| 43 |
+
"status_code": "STATUS_CODE_ERROR"
|
| 44 |
+
},
|
| 45 |
+
"variants": [
|
| 46 |
+
{
|
| 47 |
+
"type": "created (fixed after human verification)",
|
| 48 |
+
"query": "rate(traces_span_metrics_calls_total{service_name=\"ad\",span_name=\"oteldemo.AdService/GetAds\",span_kind=\"SPAN_KIND_SERVER\",status_code=\"STATUS_CODE_ERROR\"}[5m])",
|
| 49 |
+
"description": "Span-derived call counter for ad-service GetAds errors. This series did not exist before the incident; it appeared when the adFailure flag began triggering StatusRuntimeException(UNAVAILABLE) with ~10% probability on every GetAds gRPC call.",
|
| 50 |
+
"onset_utc": "2026-04-19 16:40:00 UTC",
|
| 51 |
+
"onset_offset_seconds": 460,
|
| 52 |
+
"onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 16:32:19 UTC, and the first data point in the series is at 16:40:00 UTC with a non-zero value of 0.00623, indicating error spans began appearing for the ad service's GetAds endpoint. This is the first timestamp where the metric exists, marking the onset of the error signal."
|
| 53 |
+
}
|
| 54 |
+
]
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"metric_family": "http_server_duration_milliseconds",
|
| 58 |
+
"signal_layer": "propagation",
|
| 59 |
+
"defining_labels": {
|
| 60 |
+
"http_method": "GET",
|
| 61 |
+
"http_status_code": "500",
|
| 62 |
+
"service_name": "frontend"
|
| 63 |
+
},
|
| 64 |
+
"variants": [
|
| 65 |
+
{
|
| 66 |
+
"type": "created (fixed after human verification)",
|
| 67 |
+
"query": "rate(http_server_duration_milliseconds_count{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])",
|
| 68 |
+
"description": "HTTP server request count for frontend service returning 500 status. New series appeared as the ad service UNAVAILABLE errors propagate through the Next.js /api/data route handler, causing the frontend to return HTTP 500 to clients.",
|
| 69 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 70 |
+
"onset_offset_seconds": 520,
|
| 71 |
+
"onset_reasoning": "The metric is a 'created' type. Pre-incident baseline is 0. At 16:41:00, the rate rises from 0 to ~0.00476, marking the first appearance of HTTP 500 errors on the frontend service. This is approximately 9 minutes after the incident injection at 16:32:19, consistent with propagation delay."
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"type": "created (fixed after human verification)",
|
| 75 |
+
"query": "rate(http_server_duration_milliseconds_sum{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])",
|
| 76 |
+
"description": "Cumulative HTTP server request duration (ms) for frontend 500 responses. Tracks total latency of the error responses caused by the ad service failure cascade.",
|
| 77 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 78 |
+
"onset_offset_seconds": 520,
|
| 79 |
+
"onset_reasoning": "The metric is a 'created' type. Pre-incident baseline is 0. At 16:41:00 UTC the rate first rises to ~0.049, which is the first significant departure from zero after the incident time (16:32:19 UTC), indicating the onset of HTTP 500 errors on the frontend."
|
| 80 |
+
}
|
| 81 |
+
]
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"metric_family": "feature_flag_flagd_impression",
|
| 85 |
+
"signal_layer": "meta",
|
| 86 |
+
"defining_labels": {
|
| 87 |
+
"feature_flag_key": "adFailure",
|
| 88 |
+
"feature_flag_result_variant": "on"
|
| 89 |
+
},
|
| 90 |
+
"variants": [
|
| 91 |
+
{
|
| 92 |
+
"type": "created (fixed after human verification)",
|
| 93 |
+
"query": "feature_flag_flagd_impression_total{feature_flag_key=\"adFailure\",feature_flag_result_variant=\"on\"}",
|
| 94 |
+
"description": "flagd impression counter for adFailure flag with result variant 'on'. This new series appeared at 16:33 UTC when the adFailure feature flag was toggled from off to on, confirming the flag change that triggers the ad service failures.",
|
| 95 |
+
"onset_utc": "2026-04-19 16:33:00 UTC",
|
| 96 |
+
"onset_offset_seconds": 40,
|
| 97 |
+
"onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 16:33:00 UTC, approximately 1 minute after the incident time (16:32:19 UTC), indicating the feature flag was toggled on and the metric was created at that point."
|
| 98 |
+
}
|
| 99 |
+
]
|
| 100 |
+
}
|
| 101 |
+
],
|
| 102 |
+
"logs": [
|
| 103 |
+
{
|
| 104 |
+
"name": "GET /api/data → 500",
|
| 105 |
+
"description": "Between 16:37:08 and 16:39:42 UTC, GET /api/data?contextKeys={category} returned 500 errors twice (2 failures out of 20 completed /api/data requests after the incident, ~10%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~15-20 ms later.",
|
| 106 |
+
"cause": "Direct effect of the adFailure flag. pages/api/data.ts calls AdGateway.listAds, which invokes the ad service's GetAds gRPC. When adFailure is on, AdService.java:205 throws StatusRuntimeException(Status.UNAVAILABLE) with 1/10 probability (random.nextInt(10) == 0), which propagates back through the frontend gateway as a 500. The two failing requests sample different categories (telescopes, books) — each page load picks a category before the ad fetch.",
|
| 107 |
+
"source": "frontend-proxy Envoy access logs",
|
| 108 |
+
"representative_attributes": {
|
| 109 |
+
"body": "[2026-04-19T16:37:08.414Z] \"GET /api/data?contextKeys=telescopes HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 27 26 \"-\" \"python-requests/2.32.5\" \"6261b255-4f6c-9a2d-b2d6-0da5a59774b5\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41088 172.18.0.29:8080 172.18.0.28:42900 - -",
|
| 110 |
+
"event.name": "proxy.access",
|
| 111 |
+
"url.full": "http://frontend-proxy:8080/api/data?contextKeys=telescopes",
|
| 112 |
+
"url.path": "/api/data?contextKeys=telescopes",
|
| 113 |
+
"upstream.cluster": "frontend",
|
| 114 |
+
"upstream.host": "172.18.0.27:8080",
|
| 115 |
+
"destination.address": "172.18.0.27",
|
| 116 |
+
"source.address": "172.18.0.28",
|
| 117 |
+
"server.address": "172.18.0.29:8080",
|
| 118 |
+
"user_agent.original": "python-requests/2.32.5",
|
| 119 |
+
"resource.service.name": "frontend-proxy",
|
| 120 |
+
"resource.log_name": "otel_envoy_access_log",
|
| 121 |
+
"traceId": "4a9c115c071f58e00205700b7ff2b852",
|
| 122 |
+
"spanId": "bf1dc411e2a87489"
|
| 123 |
+
},
|
| 124 |
+
"log_documents": [
|
| 125 |
+
{
|
| 126 |
+
"_index": "otel-logs-2026-04-19",
|
| 127 |
+
"_id": "lIWapp0Br_RFnSwRY0tx",
|
| 128 |
+
"@timestamp": "16:37:08.414"
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"_index": "otel-logs-2026-04-19",
|
| 132 |
+
"_id": "yIWcpp0Br_RFnSwRvVEg",
|
| 133 |
+
"@timestamp": "16:39:42.669"
|
| 134 |
+
}
|
| 135 |
+
]
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"name": "ad: GetAds Failed (WARN)",
|
| 139 |
+
"description": "Between 16:37:08 and 16:39:42 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~15 ms after its corresponding /api/data 500 in the frontend-proxy access log, giving a 1:1 correspondence with the GetAds UNAVAILABLE Cascade traces (matching the 2 failing traces under that cluster). These are the only WARN-severity logs from the ad service in the incident window.",
|
| 140 |
+
"cause": "Smoking-gun direct evidence of the adFailure flag. Each time AdService.java:205 throws StatusRuntimeException(Status.UNAVAILABLE), execution enters the catch block at AdService.java:218, which calls logger.log(Level.WARN, \"GetAds Failed with status {}\", e.getStatus()) at AdService.java:222 before rethrowing to the gRPC client. The ad service explicitly names the failing RPC and echoes the UNAVAILABLE status code from the feature-flag code path.",
|
| 141 |
+
"source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)",
|
| 142 |
+
"representative_attributes": {
|
| 143 |
+
"body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}",
|
| 144 |
+
"severity.text": "WARN",
|
| 145 |
+
"severity.number": "13",
|
| 146 |
+
"instrumentationScope.name": "oteldemo.AdService",
|
| 147 |
+
"resource.service.name": "ad",
|
| 148 |
+
"resource.service.namespace": "opentelemetry-demo",
|
| 149 |
+
"resource.service.version": "2.2.0",
|
| 150 |
+
"resource.telemetry.sdk.language": "java",
|
| 151 |
+
"resource.telemetry.distro.name": "opentelemetry-java-instrumentation",
|
| 152 |
+
"traceId": "4a9c115c071f58e00205700b7ff2b852",
|
| 153 |
+
"spanId": "c8be6b167e3936cb"
|
| 154 |
+
},
|
| 155 |
+
"log_documents": [
|
| 156 |
+
{
|
| 157 |
+
"_index": "otel-logs-2026-04-19",
|
| 158 |
+
"_id": "mIWapp0Br_RFnSwRZEt3",
|
| 159 |
+
"@timestamp": "16:37:08.429"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"_index": "otel-logs-2026-04-19",
|
| 163 |
+
"_id": "0YWcpp0Br_RFnSwRvlE6",
|
| 164 |
+
"@timestamp": "16:39:42.676"
|
| 165 |
+
}
|
| 166 |
+
]
|
| 167 |
+
}
|
| 168 |
+
],
|
| 169 |
+
"frontend": [
|
| 170 |
+
{
|
| 171 |
+
"description": "The yellow ad banner at the bottom of product detail and checkout confirmation pages renders as a blank yellow box with no ad text and no link. The rest of the page loads normally — the failure is silent degradation, not a visible error.",
|
| 172 |
+
"route": "GET /api/data",
|
| 173 |
+
"deterministic": false,
|
| 174 |
+
"trigger_condition": "User visits a product detail page or checkout confirmation page, triggering an ad fetch via AdProvider. The ad service fails with 10% probability (`random.nextInt(10) == 0` in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205)).",
|
| 175 |
+
"source_file": "src/frontend/pages/api/data.ts",
|
| 176 |
+
"source_line": 15,
|
| 177 |
+
"calling_service": "frontend",
|
| 178 |
+
"call_pattern": "Single direct call: AdProvider.useQuery ([`Ad.provider.tsx#L30`](../../opentelemetry-demo/src/frontend/providers/Ad.provider.tsx#L30)) → ApiGateway.listAds ([`Api.gateway.ts#L103`](../../opentelemetry-demo/src/frontend/gateways/Api.gateway.ts#L103)) → [`data.ts#L15`](../../opentelemetry-demo/src/frontend/pages/api/data.ts#L15) → AdGateway.listAds → gRPC client.getAds ([`Ad.gateway.ts#L14`](../../opentelemetry-demo/src/frontend/gateways/rpc/Ad.gateway.ts#L14)).",
|
| 179 |
+
"cause": "The [`data.ts#L15`](../../opentelemetry-demo/src/frontend/pages/api/data.ts#L15) API route calls `AdGateway.listAds` with no try-catch. When adFailure is on and the 1/10 random gate fires, the ad service throws `StatusRuntimeException(Status.UNAVAILABLE)` at [`AdService.java#L206`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L206). The gRPC error rejects the promise in [`Ad.gateway.ts#L14`](../../opentelemetry-demo/src/frontend/gateways/rpc/Ad.gateway.ts#L14), propagates to [`InstrumentationMiddleware.ts#L23`](../../opentelemetry-demo/src/frontend/utils/telemetry/InstrumentationMiddleware.ts#L23) which records the exception on the span and re-throws, and Next.js returns HTTP 500. On the client side, React Query in [`Ad.provider.tsx#L30`](../../opentelemetry-demo/src/frontend/providers/Ad.provider.tsx#L30) catches the failure and defaults `adList` to `[]`. The Ad component ([`Ad.tsx#L10`](../../opentelemetry-demo/src/frontend/components/Ad/Ad.tsx#L10)) falls back to `{ text: '', redirectUrl: '' }`, rendering the styled yellow banner with empty content.",
|
| 180 |
+
"symptom_type": "visual_degradation"
|
| 181 |
+
}
|
| 182 |
+
],
|
| 183 |
+
"traces": [
|
| 184 |
+
{
|
| 185 |
+
"name": "GetAds UNAVAILABLE Cascade",
|
| 186 |
+
"description": "Between 16:37:08 and 16:39:42 UTC, 2 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. Both traces have root operation load-generator:user_get_ads. The failures land roughly 2.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.",
|
| 187 |
+
"cause": "Direct effect of the adFailure flag. When adFailure is on, AdService.java:205 throws StatusRuntimeException(Status.UNAVAILABLE) with 1/10 probability (random.nextInt(10) == 0). The exception is caught at AdService.java:218, logged as WARN at line 222, then surfaced to the gRPC client via responseObserver.onError(...). The error propagates through frontend's AdGateway to the Next.js /api/data route handler, which returns HTTP 500, and finally back out through the frontend-proxy Envoy to the load generator.",
|
| 188 |
+
"call_chain": "ad:oteldemo.AdService/GetAds → frontend:oteldemo.AdService/GetAds → frontend:executing api route (pages) /api/data → frontend:GET /api/data → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET",
|
| 189 |
+
"smoking_gun": [
|
| 190 |
+
"ad:oteldemo.AdService/GetAds span: otel.status_code=ERROR, rpc.grpc.status_code=14, rpc.service=oteldemo.AdService, rpc.method=GetAds, and log event {event: \"Error\", exception.message: \"UNAVAILABLE\"} — no description, no stacktrace, matching the bare `throw new StatusRuntimeException(Status.UNAVAILABLE)` at AdService.java:206",
|
| 191 |
+
"ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes] or [books], set at AdService.java:195 before the flag check at line 205 — proves execution reached the flag-triggered throw with ads already prepared (rules out upstream failures in getAdsByCategory/getRandomAds)",
|
| 192 |
+
"ad:getAdsByCategory child span completes successfully with no errors — the failure is injected by the explicit flag-triggered throw in getAds, not by any downstream dependency",
|
| 193 |
+
"frontend:oteldemo.AdService/GetAds client span carries the received gRPC error as tag grpc.error_message=\"14 UNAVAILABLE: \" with rpc.grpc.status_code=14 (trailing colon with empty description, characteristic of the Java server not calling .withDescription(...))"
|
| 194 |
+
],
|
| 195 |
+
"trace_documents": [
|
| 196 |
+
{
|
| 197 |
+
"traceID": "4a9c115c071f58e00205700b7ff2b852",
|
| 198 |
+
"@timestamp": "16:37:08",
|
| 199 |
+
"user_action": "user_get_ads"
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"traceID": "bec127aafcab40a93d1d79411951afd7",
|
| 203 |
+
"@timestamp": "16:39:42",
|
| 204 |
+
"user_action": "user_get_ads"
|
| 205 |
+
}
|
| 206 |
+
]
|
| 207 |
+
}
|
| 208 |
+
]
|
| 209 |
+
}
|
| 210 |
+
}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate an incident report from a rubric JSON via LLM.
|
| 3 |
+
|
| 4 |
+
Standalone script designed to run inside a Harbor task container.
|
| 5 |
+
Also importable by ``run_solve.py`` for local batch generation.
|
| 6 |
+
|
| 7 |
+
Examples::
|
| 8 |
+
|
| 9 |
+
# Inside Harbor container (solve.sh calls this):
|
| 10 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md
|
| 11 |
+
|
| 12 |
+
# With custom model/effort:
|
| 13 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import asyncio
|
| 18 |
+
import json
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from check_prediction import async_call_llm_judge, format_rubric
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
DEFAULT_MODEL: str | None = None
|
| 29 |
+
DEFAULT_EFFORT = "high"
|
| 30 |
+
|
| 31 |
+
# Report format from harbor-template/instruction.md.template — sections 1-4.
|
| 32 |
+
REPORT_FORMAT = """\
|
| 33 |
+
Write a structured incident report with four sections: Summary, Timeline, \
|
| 34 |
+
5 Whys, and Remediation. Follow all section-specific rules below.
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
## Section 1: Summary
|
| 39 |
+
|
| 40 |
+
2-3 sentences describing what happened, when, and the high-level impact. \
|
| 41 |
+
This should be understandable by someone unfamiliar with the system. Focus \
|
| 42 |
+
on what DID happen and the observable impact — mention request failures if \
|
| 43 |
+
they occurred, but do NOT mention the absence of failures or errors as this \
|
| 44 |
+
can be misread and cause confusion. You may name the root cause in a single \
|
| 45 |
+
phrase (e.g. "due to a misconfigured batch job") but do not explain the \
|
| 46 |
+
causal chain — that belongs in the 5 Whys section.
|
| 47 |
+
|
| 48 |
+
Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \
|
| 49 |
+
503 errors for 14% of checkout requests, affecting paying users, due to a \
|
| 50 |
+
Redis cache eviction. The full causal chain is detailed in the 5 Whys section \
|
| 51 |
+
below."
|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
## Section 2: Timeline
|
| 56 |
+
|
| 57 |
+
A chronological narrative of ONLY what went wrong, reconstructed from the \
|
| 58 |
+
provided telemetry. Each entry should be a single succinct line. Cover \
|
| 59 |
+
higher-level events — when a change was introduced, when symptoms started, \
|
| 60 |
+
when a change was reverted, when symptoms subsided — not individual error \
|
| 61 |
+
occurrences. The first entry should be the earliest anomaly visible in the \
|
| 62 |
+
provided telemetry; this establishes the incident start time referenced by \
|
| 63 |
+
the Summary and 5 Whys sections.
|
| 64 |
+
|
| 65 |
+
For each entry:
|
| 66 |
+
- State the time (UTC), the service(s) involved, and what happened
|
| 67 |
+
- Quantify where possible (error rate, duration, number of affected requests)
|
| 68 |
+
- Do NOT include normal/healthy behavior, baseline noise, or things that \
|
| 69 |
+
worked correctly
|
| 70 |
+
|
| 71 |
+
Example format:
|
| 72 |
+
```
|
| 73 |
+
09:44 UTC — analytics-job deployed with no memory limit set
|
| 74 |
+
14:17 UTC — redis-cache-0 OOMKilled; node memory at 97%
|
| 75 |
+
14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres
|
| 76 |
+
14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14%
|
| 77 |
+
14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
---
|
| 81 |
+
|
| 82 |
+
## Section 3: 5 Whys
|
| 83 |
+
|
| 84 |
+
Rules:
|
| 85 |
+
1. Start by stating the problem as a precise, observable symptom — not a \
|
| 86 |
+
cause. Include what failed, when, and impact (error rate, affected users, \
|
| 87 |
+
duration).
|
| 88 |
+
2. Each "why" answer must be grounded in the provided telemetry. Cite only \
|
| 89 |
+
the telemetry types relevant to that step, using the format below for each.
|
| 90 |
+
|
| 91 |
+
- Metrics: one sentence describing the baseline value (or typical range), \
|
| 92 |
+
what it changed to, and at what UTC timestamp. Where relevant, include rate \
|
| 93 |
+
of change or duration. Follow with the exact PromQL query that would surface it.
|
| 94 |
+
Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \
|
| 95 |
+
14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\
|
| 96 |
+
status=~"5.."}[1m])"
|
| 97 |
+
|
| 98 |
+
- Traces: the cascade from the highest-level operation down to the deepest \
|
| 99 |
+
failing span, followed by representative trace IDs from the provided data.
|
| 100 |
+
Example — "checkout request → order-svc goroutine exhaustion → \
|
| 101 |
+
inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736"
|
| 102 |
+
|
| 103 |
+
- Logs: one sentence with service, endpoint, error, and time range, \
|
| 104 |
+
followed by the exact Lucene query that would retrieve the relevant log lines.
|
| 105 |
+
Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \
|
| 106 |
+
returned 503s. Lucene: service:order-svc AND status:503 AND \
|
| 107 |
+
endpoint:\\"/api/checkout\\""
|
| 108 |
+
3. Each "why" targets the previous answer, not the original problem. Drill \
|
| 109 |
+
down one causal chain; do not branch.
|
| 110 |
+
4. Never accept "human error" or "operator mistake" as a terminal answer. \
|
| 111 |
+
Ask why the human was in a position to make that error.
|
| 112 |
+
5. Stop when you reach a cause that is: (a) actionable — something a team \
|
| 113 |
+
can change, or (b) a process or system gap that allowed the failure to \
|
| 114 |
+
propagate. The number of steps is not fixed at 5.
|
| 115 |
+
6. Only include steps that are directly supported by the provided telemetry. \
|
| 116 |
+
If the causal chain cannot be completed with the available evidence, stop \
|
| 117 |
+
and note what additional telemetry would be needed to continue.
|
| 118 |
+
7. After the chain, note any branches you did NOT follow. If the incident \
|
| 119 |
+
has multiple contributing causes that cannot fit a single chain, say so \
|
| 120 |
+
explicitly rather than forcing one.
|
| 121 |
+
|
| 122 |
+
Output format:
|
| 123 |
+
|
| 124 |
+
```
|
| 125 |
+
Problem statement:
|
| 126 |
+
[Observable symptom with time, impact, and detection method]
|
| 127 |
+
|
| 128 |
+
Why 1: [question] → [answer]
|
| 129 |
+
Evidence: [specific signal]
|
| 130 |
+
|
| 131 |
+
Why 2: [question] → [answer]
|
| 132 |
+
Evidence: [specific signal]
|
| 133 |
+
|
| 134 |
+
...
|
| 135 |
+
|
| 136 |
+
Root cause:
|
| 137 |
+
[Single sentence naming the systemic or process failure]
|
| 138 |
+
|
| 139 |
+
Unexplored branches:
|
| 140 |
+
[Contributing factors visible in telemetry that were not followed, \
|
| 141 |
+
and why they were set aside]
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
## Section 4: Remediation
|
| 147 |
+
|
| 148 |
+
For each corrective action, identify which step in the causal chain it \
|
| 149 |
+
targets and what class of fix it is:
|
| 150 |
+
|
| 151 |
+
- **Root cause fix**: eliminates the condition that started the chain
|
| 152 |
+
- **Propagation fix**: limits blast radius if the root cause recurs
|
| 153 |
+
- **Detection fix**: reduces time-to-detect or time-to-mitigate
|
| 154 |
+
|
| 155 |
+
List actions from root cause outward. Prefer fixes that prevent recurrence \
|
| 156 |
+
over fixes that only improve response.
|
| 157 |
+
|
| 158 |
+
Output format:
|
| 159 |
+
|
| 160 |
+
| Action | Targets | Type |
|
| 161 |
+
|--------|---------|------|
|
| 162 |
+
| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix |
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
SOLUTION_PROMPT_TEMPLATE = """\
|
| 166 |
+
You are an expert site reliability engineer. You are given a ground-truth \
|
| 167 |
+
rubric describing an incident's root cause, mechanism, and telemetry evidence.
|
| 168 |
+
|
| 169 |
+
Your task: write an incident report as if you investigated this incident \
|
| 170 |
+
yourself. Use the rubric evidence to populate each section. Do NOT mention \
|
| 171 |
+
the rubric or that you were given ground-truth data — write as though you \
|
| 172 |
+
discovered everything through telemetry analysis.
|
| 173 |
+
|
| 174 |
+
## Ground-Truth Rubric
|
| 175 |
+
|
| 176 |
+
{rubric}
|
| 177 |
+
|
| 178 |
+
## Report Format
|
| 179 |
+
|
| 180 |
+
{report_format}
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def build_solution_prompt(rubric_md: str) -> str:
|
| 185 |
+
"""Build the LLM prompt from a formatted rubric markdown string."""
|
| 186 |
+
return SOLUTION_PROMPT_TEMPLATE.format(
|
| 187 |
+
rubric=rubric_md,
|
| 188 |
+
report_format=REPORT_FORMAT,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
async def generate_report(
|
| 193 |
+
client: Any,
|
| 194 |
+
rubric_data: dict,
|
| 195 |
+
model: str | None = DEFAULT_MODEL,
|
| 196 |
+
effort: str | None = DEFAULT_EFFORT,
|
| 197 |
+
) -> tuple[str, str, list[dict] | None]:
|
| 198 |
+
"""Generate an incident report from rubric JSON.
|
| 199 |
+
|
| 200 |
+
If ``model`` is ``None``, the formatted rubric is returned directly with
|
| 201 |
+
no LLM call. Otherwise the rubric is passed to the LLM to be reformatted
|
| 202 |
+
into an incident report.
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
A tuple of (report_text, prompt, reasoning_summary). When ``model``
|
| 206 |
+
is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``.
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
rubric_md = format_rubric(rubric_data)
|
| 210 |
+
if model is None:
|
| 211 |
+
return rubric_md, "", None
|
| 212 |
+
prompt = build_solution_prompt(rubric_md)
|
| 213 |
+
response_text, reasoning_summary = await async_call_llm_judge(
|
| 214 |
+
client, prompt, model=model, reasoning_effort=effort
|
| 215 |
+
)
|
| 216 |
+
return response_text, prompt, reasoning_summary
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
async def async_main() -> None:
|
| 220 |
+
"""CLI entry point: read rubric, call LLM, write report."""
|
| 221 |
+
parser = argparse.ArgumentParser(
|
| 222 |
+
description="Generate an incident report from a rubric JSON via LLM."
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--rubric",
|
| 226 |
+
type=str,
|
| 227 |
+
default="/tests/rubric.json",
|
| 228 |
+
help="Path to rubric JSON file.",
|
| 229 |
+
)
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--output",
|
| 232 |
+
type=str,
|
| 233 |
+
default="/app/report.md",
|
| 234 |
+
help="Path to write the generated report.",
|
| 235 |
+
)
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--model",
|
| 238 |
+
"-m",
|
| 239 |
+
type=str,
|
| 240 |
+
default=DEFAULT_MODEL,
|
| 241 |
+
help=(
|
| 242 |
+
"LLM model name. If omitted, the formatted rubric is written "
|
| 243 |
+
"directly as the report with no LLM call."
|
| 244 |
+
),
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--effort",
|
| 248 |
+
"-e",
|
| 249 |
+
type=str,
|
| 250 |
+
choices=["low", "medium", "high"],
|
| 251 |
+
default=DEFAULT_EFFORT,
|
| 252 |
+
help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).",
|
| 253 |
+
)
|
| 254 |
+
args = parser.parse_args()
|
| 255 |
+
|
| 256 |
+
logging.basicConfig(
|
| 257 |
+
level=logging.INFO,
|
| 258 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
rubric_path = Path(args.rubric)
|
| 262 |
+
output_path = Path(args.output)
|
| 263 |
+
|
| 264 |
+
if not rubric_path.is_file():
|
| 265 |
+
logger.warning(f"Rubric file not found: {rubric_path}; writing empty report")
|
| 266 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 267 |
+
output_path.write_text("")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
rubric_data = json.loads(rubric_path.read_text())
|
| 271 |
+
logger.info(
|
| 272 |
+
f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} "
|
| 273 |
+
f"from {rubric_path}"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
client: Any = None
|
| 277 |
+
if args.model is not None:
|
| 278 |
+
from openai import AsyncOpenAI
|
| 279 |
+
|
| 280 |
+
client = AsyncOpenAI(
|
| 281 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 282 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
report_text, _prompt, reasoning_summary = await generate_report(
|
| 286 |
+
client, rubric_data, model=args.model, effort=args.effort
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 290 |
+
output_path.write_text(report_text)
|
| 291 |
+
logger.info(f"Wrote report to {output_path}")
|
| 292 |
+
|
| 293 |
+
if reasoning_summary:
|
| 294 |
+
logger.info(f"Reasoning summary: {reasoning_summary}")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
if __name__ == "__main__":
|
| 298 |
+
asyncio.run(async_main())
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# ── Wait for the entrypoint to finish setting up the environment ──
|
| 5 |
+
echo "[solve] Waiting for environment to be ready..."
|
| 6 |
+
for i in $(seq 1 180); do
|
| 7 |
+
[ -f /tmp/env-ready ] && break
|
| 8 |
+
sleep 1
|
| 9 |
+
done
|
| 10 |
+
if [ ! -f /tmp/env-ready ]; then
|
| 11 |
+
echo "[solve] ERROR: Environment did not become ready within 180s" >&2
|
| 12 |
+
exit 1
|
| 13 |
+
fi
|
| 14 |
+
echo "[solve] Environment is ready."
|
| 15 |
+
|
| 16 |
+
# ── Verify all services are healthy ──
|
| 17 |
+
echo "[solve] Running health checks..."
|
| 18 |
+
source /tmp/env-ports
|
| 19 |
+
/app/check_health.sh || {
|
| 20 |
+
echo "[solve] ERROR: Health checks failed" >&2
|
| 21 |
+
exit 1
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# ── Generate solution report via LLM ──
|
| 25 |
+
echo "[solve] Installing dependencies..."
|
| 26 |
+
pip install tabulate
|
| 27 |
+
echo "[solve] Generating report..."
|
| 28 |
+
python /solution/solve.py --rubric /solution/rubric.json
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"events": [
|
| 3 |
+
{
|
| 4 |
+
"event_id": "d1-i1-imageSlowLoad-on",
|
| 5 |
+
"root_cause": "imageSlowLoad",
|
| 6 |
+
"event_time": "2026-04-19T14:01:51.404464+00:00"
|
| 7 |
+
},
|
| 8 |
+
{
|
| 9 |
+
"event_id": "d1-i2-adFailure-on",
|
| 10 |
+
"root_cause": "adFailure",
|
| 11 |
+
"event_time": "2026-04-19T16:32:19.033653+00:00"
|
| 12 |
+
}
|
| 13 |
+
]
|
| 14 |
+
}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T16:32:19.033653+00:00",
|
| 3 |
+
"feature_flag": "adFailure",
|
| 4 |
+
"description": "A feature flag in the ad service's `GetAds` handler threw `StatusRuntimeException(Status.UNAVAILABLE)` on ~10% of calls (`random.nextInt(10) == 0`); the frontend `/api/data` route caught the gRPC error and returned HTTP 500, but React Query's default `adList = []` fallback masked the failure in the UI — the yellow ad banner silently rendered blank rather than showing an error.",
|
| 5 |
+
"mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205): on every `getAds` gRPC call, after ads have been collected and the request/response type attributes set, the service evaluates `ffClient.getBooleanValue(\"adFailure\", false, evaluationContext)`. When `true`, it throws `StatusRuntimeException(Status.UNAVAILABLE)` with probability 1/10 (`random.nextInt(10) == 0`) at [`AdService.java#L206`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L206).\n\nThe exception is caught at [`AdService.java#L218`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L218): the catch block adds an \"Error\" span event (line 219-220), sets the span status to ERROR (line 221), logs a WARN \"GetAds Failed with status {UNAVAILABLE}\" (line 222), and calls `responseObserver.onError(e)` (line 223) which sends the gRPC UNAVAILABLE status back to the caller.\n\nThe frontend calls the ad service via [`Ad.gateway.ts#L14`](../../opentelemetry-demo/src/frontend/gateways/rpc/Ad.gateway.ts#L14) (`client.getAds`), invoked from the `/api/data` route at [`data.ts#L15`](../../opentelemetry-demo/src/frontend/pages/api/data.ts#L15). When the gRPC call fails, the error propagates through the Next.js API route as an unhandled rejection, and the frontend-proxy Envoy returns HTTP 500 to the client.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [
|
| 8 |
+
{
|
| 9 |
+
"metric_family": "rpc_server_duration_milliseconds",
|
| 10 |
+
"signal_layer": "root_cause",
|
| 11 |
+
"defining_labels": {
|
| 12 |
+
"rpc_grpc_status_code": "14",
|
| 13 |
+
"rpc_method": "GetAds",
|
| 14 |
+
"rpc_service": "oteldemo.AdService",
|
| 15 |
+
"service_name": "ad"
|
| 16 |
+
},
|
| 17 |
+
"variants": [
|
| 18 |
+
{
|
| 19 |
+
"type": "created (fixed after human verification)",
|
| 20 |
+
"query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])",
|
| 21 |
+
"description": "gRPC server call count for AdService/GetAds with status code 14 (UNAVAILABLE). This new series appeared because the adFailure flag causes AdService.java to throw StatusRuntimeException(Status.UNAVAILABLE) with 1/10 probability on each GetAds call.",
|
| 22 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 23 |
+
"onset_offset_seconds": 520,
|
| 24 |
+
"onset_reasoning": "The metric type is 'created'. Pre-incident baseline is 0. At 16:41:00 UTC the rate first rises above zero (0.0048), approximately 9 minutes after the incident time. This is the first appearance of rpc_grpc_status_code=14 (UNAVAILABLE) errors for the AdService, indicating the onset of the fault."
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"type": "created (fixed after human verification)",
|
| 28 |
+
"query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])",
|
| 29 |
+
"description": "Cumulative gRPC server call duration (ms) for AdService/GetAds UNAVAILABLE errors. Tracks the total latency of the failed GetAds RPCs triggered by the adFailure flag.",
|
| 30 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 31 |
+
"onset_offset_seconds": 520,
|
| 32 |
+
"onset_reasoning": "The metric type is 'created'. Pre-incident baseline is 0. At 16:41:00 UTC the value first rises to 0.0145643, which is the first non-zero reading after the incident time (16:32:19 UTC), indicating the onset of rpc_server_duration for status_code=14 (UNAVAILABLE) errors on AdService.GetAds."
|
| 33 |
+
}
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"metric_family": "traces_span_metrics_calls",
|
| 38 |
+
"signal_layer": "root_cause",
|
| 39 |
+
"defining_labels": {
|
| 40 |
+
"service_name": "ad",
|
| 41 |
+
"span_kind": "SPAN_KIND_SERVER",
|
| 42 |
+
"span_name": "oteldemo.AdService/GetAds",
|
| 43 |
+
"status_code": "STATUS_CODE_ERROR"
|
| 44 |
+
},
|
| 45 |
+
"variants": [
|
| 46 |
+
{
|
| 47 |
+
"type": "created (fixed after human verification)",
|
| 48 |
+
"query": "rate(traces_span_metrics_calls_total{service_name=\"ad\",span_name=\"oteldemo.AdService/GetAds\",span_kind=\"SPAN_KIND_SERVER\",status_code=\"STATUS_CODE_ERROR\"}[5m])",
|
| 49 |
+
"description": "Span-derived call counter for ad-service GetAds errors. This series did not exist before the incident; it appeared when the adFailure flag began triggering StatusRuntimeException(UNAVAILABLE) with ~10% probability on every GetAds gRPC call.",
|
| 50 |
+
"onset_utc": "2026-04-19 16:40:00 UTC",
|
| 51 |
+
"onset_offset_seconds": 460,
|
| 52 |
+
"onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 16:32:19 UTC, and the first data point in the series is at 16:40:00 UTC with a non-zero value of 0.00623, indicating error spans began appearing for the ad service's GetAds endpoint. This is the first timestamp where the metric exists, marking the onset of the error signal."
|
| 53 |
+
}
|
| 54 |
+
]
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"metric_family": "http_server_duration_milliseconds",
|
| 58 |
+
"signal_layer": "propagation",
|
| 59 |
+
"defining_labels": {
|
| 60 |
+
"http_method": "GET",
|
| 61 |
+
"http_status_code": "500",
|
| 62 |
+
"service_name": "frontend"
|
| 63 |
+
},
|
| 64 |
+
"variants": [
|
| 65 |
+
{
|
| 66 |
+
"type": "created (fixed after human verification)",
|
| 67 |
+
"query": "rate(http_server_duration_milliseconds_count{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])",
|
| 68 |
+
"description": "HTTP server request count for frontend service returning 500 status. New series appeared as the ad service UNAVAILABLE errors propagate through the Next.js /api/data route handler, causing the frontend to return HTTP 500 to clients.",
|
| 69 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 70 |
+
"onset_offset_seconds": 520,
|
| 71 |
+
"onset_reasoning": "The metric is a 'created' type. Pre-incident baseline is 0. At 16:41:00, the rate rises from 0 to ~0.00476, marking the first appearance of HTTP 500 errors on the frontend service. This is approximately 9 minutes after the incident injection at 16:32:19, consistent with propagation delay."
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"type": "created (fixed after human verification)",
|
| 75 |
+
"query": "rate(http_server_duration_milliseconds_sum{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])",
|
| 76 |
+
"description": "Cumulative HTTP server request duration (ms) for frontend 500 responses. Tracks total latency of the error responses caused by the ad service failure cascade.",
|
| 77 |
+
"onset_utc": "2026-04-19 16:41:00 UTC",
|
| 78 |
+
"onset_offset_seconds": 520,
|
| 79 |
+
"onset_reasoning": "The metric is a 'created' type. Pre-incident baseline is 0. At 16:41:00 UTC the rate first rises to ~0.049, which is the first significant departure from zero after the incident time (16:32:19 UTC), indicating the onset of HTTP 500 errors on the frontend."
|
| 80 |
+
}
|
| 81 |
+
]
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"metric_family": "feature_flag_flagd_impression",
|
| 85 |
+
"signal_layer": "meta",
|
| 86 |
+
"defining_labels": {
|
| 87 |
+
"feature_flag_key": "adFailure",
|
| 88 |
+
"feature_flag_result_variant": "on"
|
| 89 |
+
},
|
| 90 |
+
"variants": [
|
| 91 |
+
{
|
| 92 |
+
"type": "created (fixed after human verification)",
|
| 93 |
+
"query": "feature_flag_flagd_impression_total{feature_flag_key=\"adFailure\",feature_flag_result_variant=\"on\"}",
|
| 94 |
+
"description": "flagd impression counter for adFailure flag with result variant 'on'. This new series appeared at 16:33 UTC when the adFailure feature flag was toggled from off to on, confirming the flag change that triggers the ad service failures.",
|
| 95 |
+
"onset_utc": "2026-04-19 16:33:00 UTC",
|
| 96 |
+
"onset_offset_seconds": 40,
|
| 97 |
+
"onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 16:33:00 UTC, approximately 1 minute after the incident time (16:32:19 UTC), indicating the feature flag was toggled on and the metric was created at that point."
|
| 98 |
+
}
|
| 99 |
+
]
|
| 100 |
+
}
|
| 101 |
+
],
|
| 102 |
+
"logs": [
|
| 103 |
+
{
|
| 104 |
+
"name": "GET /api/data → 500",
|
| 105 |
+
"description": "Between 16:37:08 and 16:39:42 UTC, GET /api/data?contextKeys={category} returned 500 errors twice (2 failures out of 20 completed /api/data requests after the incident, ~10%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~15-20 ms later.",
|
| 106 |
+
"cause": "Direct effect of the adFailure flag. pages/api/data.ts calls AdGateway.listAds, which invokes the ad service's GetAds gRPC. When adFailure is on, AdService.java:205 throws StatusRuntimeException(Status.UNAVAILABLE) with 1/10 probability (random.nextInt(10) == 0), which propagates back through the frontend gateway as a 500. The two failing requests sample different categories (telescopes, books) — each page load picks a category before the ad fetch.",
|
| 107 |
+
"source": "frontend-proxy Envoy access logs",
|
| 108 |
+
"representative_attributes": {
|
| 109 |
+
"body": "[2026-04-19T16:37:08.414Z] \"GET /api/data?contextKeys=telescopes HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 27 26 \"-\" \"python-requests/2.32.5\" \"6261b255-4f6c-9a2d-b2d6-0da5a59774b5\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41088 172.18.0.29:8080 172.18.0.28:42900 - -",
|
| 110 |
+
"event.name": "proxy.access",
|
| 111 |
+
"url.full": "http://frontend-proxy:8080/api/data?contextKeys=telescopes",
|
| 112 |
+
"url.path": "/api/data?contextKeys=telescopes",
|
| 113 |
+
"upstream.cluster": "frontend",
|
| 114 |
+
"upstream.host": "172.18.0.27:8080",
|
| 115 |
+
"destination.address": "172.18.0.27",
|
| 116 |
+
"source.address": "172.18.0.28",
|
| 117 |
+
"server.address": "172.18.0.29:8080",
|
| 118 |
+
"user_agent.original": "python-requests/2.32.5",
|
| 119 |
+
"resource.service.name": "frontend-proxy",
|
| 120 |
+
"resource.log_name": "otel_envoy_access_log",
|
| 121 |
+
"traceId": "4a9c115c071f58e00205700b7ff2b852",
|
| 122 |
+
"spanId": "bf1dc411e2a87489"
|
| 123 |
+
},
|
| 124 |
+
"log_documents": [
|
| 125 |
+
{
|
| 126 |
+
"_index": "otel-logs-2026-04-19",
|
| 127 |
+
"_id": "lIWapp0Br_RFnSwRY0tx",
|
| 128 |
+
"@timestamp": "16:37:08.414"
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"_index": "otel-logs-2026-04-19",
|
| 132 |
+
"_id": "yIWcpp0Br_RFnSwRvVEg",
|
| 133 |
+
"@timestamp": "16:39:42.669"
|
| 134 |
+
}
|
| 135 |
+
]
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"name": "ad: GetAds Failed (WARN)",
|
| 139 |
+
"description": "Between 16:37:08 and 16:39:42 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~15 ms after its corresponding /api/data 500 in the frontend-proxy access log, giving a 1:1 correspondence with the GetAds UNAVAILABLE Cascade traces (matching the 2 failing traces under that cluster). These are the only WARN-severity logs from the ad service in the incident window.",
|
| 140 |
+
"cause": "Smoking-gun direct evidence of the adFailure flag. Each time AdService.java:205 throws StatusRuntimeException(Status.UNAVAILABLE), execution enters the catch block at AdService.java:218, which calls logger.log(Level.WARN, \"GetAds Failed with status {}\", e.getStatus()) at AdService.java:222 before rethrowing to the gRPC client. The ad service explicitly names the failing RPC and echoes the UNAVAILABLE status code from the feature-flag code path.",
|
| 141 |
+
"source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)",
|
| 142 |
+
"representative_attributes": {
|
| 143 |
+
"body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}",
|
| 144 |
+
"severity.text": "WARN",
|
| 145 |
+
"severity.number": "13",
|
| 146 |
+
"instrumentationScope.name": "oteldemo.AdService",
|
| 147 |
+
"resource.service.name": "ad",
|
| 148 |
+
"resource.service.namespace": "opentelemetry-demo",
|
| 149 |
+
"resource.service.version": "2.2.0",
|
| 150 |
+
"resource.telemetry.sdk.language": "java",
|
| 151 |
+
"resource.telemetry.distro.name": "opentelemetry-java-instrumentation",
|
| 152 |
+
"traceId": "4a9c115c071f58e00205700b7ff2b852",
|
| 153 |
+
"spanId": "c8be6b167e3936cb"
|
| 154 |
+
},
|
| 155 |
+
"log_documents": [
|
| 156 |
+
{
|
| 157 |
+
"_index": "otel-logs-2026-04-19",
|
| 158 |
+
"_id": "mIWapp0Br_RFnSwRZEt3",
|
| 159 |
+
"@timestamp": "16:37:08.429"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"_index": "otel-logs-2026-04-19",
|
| 163 |
+
"_id": "0YWcpp0Br_RFnSwRvlE6",
|
| 164 |
+
"@timestamp": "16:39:42.676"
|
| 165 |
+
}
|
| 166 |
+
]
|
| 167 |
+
}
|
| 168 |
+
],
|
| 169 |
+
"frontend": [
|
| 170 |
+
{
|
| 171 |
+
"description": "The yellow ad banner at the bottom of product detail and checkout confirmation pages renders as a blank yellow box with no ad text and no link. The rest of the page loads normally — the failure is silent degradation, not a visible error.",
|
| 172 |
+
"route": "GET /api/data",
|
| 173 |
+
"deterministic": false,
|
| 174 |
+
"trigger_condition": "User visits a product detail page or checkout confirmation page, triggering an ad fetch via AdProvider. The ad service fails with 10% probability (`random.nextInt(10) == 0` in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205)).",
|
| 175 |
+
"source_file": "src/frontend/pages/api/data.ts",
|
| 176 |
+
"source_line": 15,
|
| 177 |
+
"calling_service": "frontend",
|
| 178 |
+
"call_pattern": "Single direct call: AdProvider.useQuery ([`Ad.provider.tsx#L30`](../../opentelemetry-demo/src/frontend/providers/Ad.provider.tsx#L30)) → ApiGateway.listAds ([`Api.gateway.ts#L103`](../../opentelemetry-demo/src/frontend/gateways/Api.gateway.ts#L103)) → [`data.ts#L15`](../../opentelemetry-demo/src/frontend/pages/api/data.ts#L15) → AdGateway.listAds → gRPC client.getAds ([`Ad.gateway.ts#L14`](../../opentelemetry-demo/src/frontend/gateways/rpc/Ad.gateway.ts#L14)).",
|
| 179 |
+
"cause": "The [`data.ts#L15`](../../opentelemetry-demo/src/frontend/pages/api/data.ts#L15) API route calls `AdGateway.listAds` with no try-catch. When adFailure is on and the 1/10 random gate fires, the ad service throws `StatusRuntimeException(Status.UNAVAILABLE)` at [`AdService.java#L206`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L206). The gRPC error rejects the promise in [`Ad.gateway.ts#L14`](../../opentelemetry-demo/src/frontend/gateways/rpc/Ad.gateway.ts#L14), propagates to [`InstrumentationMiddleware.ts#L23`](../../opentelemetry-demo/src/frontend/utils/telemetry/InstrumentationMiddleware.ts#L23) which records the exception on the span and re-throws, and Next.js returns HTTP 500. On the client side, React Query in [`Ad.provider.tsx#L30`](../../opentelemetry-demo/src/frontend/providers/Ad.provider.tsx#L30) catches the failure and defaults `adList` to `[]`. The Ad component ([`Ad.tsx#L10`](../../opentelemetry-demo/src/frontend/components/Ad/Ad.tsx#L10)) falls back to `{ text: '', redirectUrl: '' }`, rendering the styled yellow banner with empty content.",
|
| 180 |
+
"symptom_type": "visual_degradation"
|
| 181 |
+
}
|
| 182 |
+
],
|
| 183 |
+
"traces": [
|
| 184 |
+
{
|
| 185 |
+
"name": "GetAds UNAVAILABLE Cascade",
|
| 186 |
+
"description": "Between 16:37:08 and 16:39:42 UTC, 2 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. Both traces have root operation load-generator:user_get_ads. The failures land roughly 2.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.",
|
| 187 |
+
"cause": "Direct effect of the adFailure flag. When adFailure is on, AdService.java:205 throws StatusRuntimeException(Status.UNAVAILABLE) with 1/10 probability (random.nextInt(10) == 0). The exception is caught at AdService.java:218, logged as WARN at line 222, then surfaced to the gRPC client via responseObserver.onError(...). The error propagates through frontend's AdGateway to the Next.js /api/data route handler, which returns HTTP 500, and finally back out through the frontend-proxy Envoy to the load generator.",
|
| 188 |
+
"call_chain": "ad:oteldemo.AdService/GetAds → frontend:oteldemo.AdService/GetAds → frontend:executing api route (pages) /api/data → frontend:GET /api/data → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET",
|
| 189 |
+
"smoking_gun": [
|
| 190 |
+
"ad:oteldemo.AdService/GetAds span: otel.status_code=ERROR, rpc.grpc.status_code=14, rpc.service=oteldemo.AdService, rpc.method=GetAds, and log event {event: \"Error\", exception.message: \"UNAVAILABLE\"} — no description, no stacktrace, matching the bare `throw new StatusRuntimeException(Status.UNAVAILABLE)` at AdService.java:206",
|
| 191 |
+
"ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes] or [books], set at AdService.java:195 before the flag check at line 205 — proves execution reached the flag-triggered throw with ads already prepared (rules out upstream failures in getAdsByCategory/getRandomAds)",
|
| 192 |
+
"ad:getAdsByCategory child span completes successfully with no errors — the failure is injected by the explicit flag-triggered throw in getAds, not by any downstream dependency",
|
| 193 |
+
"frontend:oteldemo.AdService/GetAds client span carries the received gRPC error as tag grpc.error_message=\"14 UNAVAILABLE: \" with rpc.grpc.status_code=14 (trailing colon with empty description, characteristic of the Java server not calling .withDescription(...))"
|
| 194 |
+
],
|
| 195 |
+
"trace_documents": [
|
| 196 |
+
{
|
| 197 |
+
"traceID": "4a9c115c071f58e00205700b7ff2b852",
|
| 198 |
+
"@timestamp": "16:37:08",
|
| 199 |
+
"user_action": "user_get_ads"
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"traceID": "bec127aafcab40a93d1d79411951afd7",
|
| 203 |
+
"@timestamp": "16:39:42",
|
| 204 |
+
"user_action": "user_get_ads"
|
| 205 |
+
}
|
| 206 |
+
]
|
| 207 |
+
}
|
| 208 |
+
]
|
| 209 |
+
}
|
| 210 |
+
}
|
tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
set +e
|
| 5 |
+
python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt
|
| 6 |
+
status=${PIPESTATUS[0]}
|
| 7 |
+
set -e
|
| 8 |
+
|
| 9 |
+
# Preserve agent predictions even on verifier failure (Harbor deletes containers).
|
| 10 |
+
if [[ -f /app/report.md ]]; then
|
| 11 |
+
mkdir -p /logs/verifier
|
| 12 |
+
cp /app/report.md /logs/verifier/report.md 2>/dev/null || true
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
if [[ -f /app/task_meta.json ]]; then
|
| 16 |
+
cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
exit $status
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
FROM ag2435/sre-otel-snapshot:{code_tag}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
build:
|
| 4 |
+
context: ${CONTEXT_DIR}
|
| 5 |
+
pull: true
|
| 6 |
+
image: ${MAIN_IMAGE_NAME}
|
| 7 |
+
command: [ "sh", "-c", "sleep infinity" ]
|
| 8 |
+
privileged: true
|
| 9 |
+
environment:
|
| 10 |
+
- TEST_DIR=${TEST_DIR}
|
| 11 |
+
- CONTEXT_DIR=${CONTEXT_DIR}
|
| 12 |
+
volumes:
|
| 13 |
+
- /var/run/docker.sock:/var/run/docker.sock
|
| 14 |
+
- ${CONTEXT_DIR}:${CONTEXT_DIR}
|
| 15 |
+
- ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH}
|
| 16 |
+
- ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH}
|
| 17 |
+
deploy:
|
| 18 |
+
resources:
|
| 19 |
+
limits:
|
| 20 |
+
cpus: ${CPUS}
|
| 21 |
+
memory: ${MEMORY}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubric.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate an incident report from a rubric JSON via LLM.
|
| 3 |
+
|
| 4 |
+
Standalone script designed to run inside a Harbor task container.
|
| 5 |
+
Also importable by ``run_solve.py`` for local batch generation.
|
| 6 |
+
|
| 7 |
+
Examples::
|
| 8 |
+
|
| 9 |
+
# Inside Harbor container (solve.sh calls this):
|
| 10 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md
|
| 11 |
+
|
| 12 |
+
# With custom model/effort:
|
| 13 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import asyncio
|
| 18 |
+
import json
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from check_prediction import async_call_llm_judge, format_rubric
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
DEFAULT_MODEL: str | None = None
|
| 29 |
+
DEFAULT_EFFORT = "high"
|
| 30 |
+
|
| 31 |
+
# Report format from harbor-template/instruction.md.template — sections 1-4.
|
| 32 |
+
REPORT_FORMAT = """\
|
| 33 |
+
Write a structured incident report with four sections: Summary, Timeline, \
|
| 34 |
+
5 Whys, and Remediation. Follow all section-specific rules below.
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
## Section 1: Summary
|
| 39 |
+
|
| 40 |
+
2-3 sentences describing what happened, when, and the high-level impact. \
|
| 41 |
+
This should be understandable by someone unfamiliar with the system. Focus \
|
| 42 |
+
on what DID happen and the observable impact — mention request failures if \
|
| 43 |
+
they occurred, but do NOT mention the absence of failures or errors as this \
|
| 44 |
+
can be misread and cause confusion. You may name the root cause in a single \
|
| 45 |
+
phrase (e.g. "due to a misconfigured batch job") but do not explain the \
|
| 46 |
+
causal chain — that belongs in the 5 Whys section.
|
| 47 |
+
|
| 48 |
+
Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \
|
| 49 |
+
503 errors for 14% of checkout requests, affecting paying users, due to a \
|
| 50 |
+
Redis cache eviction. The full causal chain is detailed in the 5 Whys section \
|
| 51 |
+
below."
|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
## Section 2: Timeline
|
| 56 |
+
|
| 57 |
+
A chronological narrative of ONLY what went wrong, reconstructed from the \
|
| 58 |
+
provided telemetry. Each entry should be a single succinct line. Cover \
|
| 59 |
+
higher-level events — when a change was introduced, when symptoms started, \
|
| 60 |
+
when a change was reverted, when symptoms subsided — not individual error \
|
| 61 |
+
occurrences. The first entry should be the earliest anomaly visible in the \
|
| 62 |
+
provided telemetry; this establishes the incident start time referenced by \
|
| 63 |
+
the Summary and 5 Whys sections.
|
| 64 |
+
|
| 65 |
+
For each entry:
|
| 66 |
+
- State the time (UTC), the service(s) involved, and what happened
|
| 67 |
+
- Quantify where possible (error rate, duration, number of affected requests)
|
| 68 |
+
- Do NOT include normal/healthy behavior, baseline noise, or things that \
|
| 69 |
+
worked correctly
|
| 70 |
+
|
| 71 |
+
Example format:
|
| 72 |
+
```
|
| 73 |
+
09:44 UTC — analytics-job deployed with no memory limit set
|
| 74 |
+
14:17 UTC — redis-cache-0 OOMKilled; node memory at 97%
|
| 75 |
+
14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres
|
| 76 |
+
14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14%
|
| 77 |
+
14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
---
|
| 81 |
+
|
| 82 |
+
## Section 3: 5 Whys
|
| 83 |
+
|
| 84 |
+
Rules:
|
| 85 |
+
1. Start by stating the problem as a precise, observable symptom — not a \
|
| 86 |
+
cause. Include what failed, when, and impact (error rate, affected users, \
|
| 87 |
+
duration).
|
| 88 |
+
2. Each "why" answer must be grounded in the provided telemetry. Cite only \
|
| 89 |
+
the telemetry types relevant to that step, using the format below for each.
|
| 90 |
+
|
| 91 |
+
- Metrics: one sentence describing the baseline value (or typical range), \
|
| 92 |
+
what it changed to, and at what UTC timestamp. Where relevant, include rate \
|
| 93 |
+
of change or duration. Follow with the exact PromQL query that would surface it.
|
| 94 |
+
Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \
|
| 95 |
+
14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\
|
| 96 |
+
status=~"5.."}[1m])"
|
| 97 |
+
|
| 98 |
+
- Traces: the cascade from the highest-level operation down to the deepest \
|
| 99 |
+
failing span, followed by representative trace IDs from the provided data.
|
| 100 |
+
Example — "checkout request → order-svc goroutine exhaustion → \
|
| 101 |
+
inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736"
|
| 102 |
+
|
| 103 |
+
- Logs: one sentence with service, endpoint, error, and time range, \
|
| 104 |
+
followed by the exact Lucene query that would retrieve the relevant log lines.
|
| 105 |
+
Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \
|
| 106 |
+
returned 503s. Lucene: service:order-svc AND status:503 AND \
|
| 107 |
+
endpoint:\\"/api/checkout\\""
|
| 108 |
+
3. Each "why" targets the previous answer, not the original problem. Drill \
|
| 109 |
+
down one causal chain; do not branch.
|
| 110 |
+
4. Never accept "human error" or "operator mistake" as a terminal answer. \
|
| 111 |
+
Ask why the human was in a position to make that error.
|
| 112 |
+
5. Stop when you reach a cause that is: (a) actionable — something a team \
|
| 113 |
+
can change, or (b) a process or system gap that allowed the failure to \
|
| 114 |
+
propagate. The number of steps is not fixed at 5.
|
| 115 |
+
6. Only include steps that are directly supported by the provided telemetry. \
|
| 116 |
+
If the causal chain cannot be completed with the available evidence, stop \
|
| 117 |
+
and note what additional telemetry would be needed to continue.
|
| 118 |
+
7. After the chain, note any branches you did NOT follow. If the incident \
|
| 119 |
+
has multiple contributing causes that cannot fit a single chain, say so \
|
| 120 |
+
explicitly rather than forcing one.
|
| 121 |
+
|
| 122 |
+
Output format:
|
| 123 |
+
|
| 124 |
+
```
|
| 125 |
+
Problem statement:
|
| 126 |
+
[Observable symptom with time, impact, and detection method]
|
| 127 |
+
|
| 128 |
+
Why 1: [question] → [answer]
|
| 129 |
+
Evidence: [specific signal]
|
| 130 |
+
|
| 131 |
+
Why 2: [question] → [answer]
|
| 132 |
+
Evidence: [specific signal]
|
| 133 |
+
|
| 134 |
+
...
|
| 135 |
+
|
| 136 |
+
Root cause:
|
| 137 |
+
[Single sentence naming the systemic or process failure]
|
| 138 |
+
|
| 139 |
+
Unexplored branches:
|
| 140 |
+
[Contributing factors visible in telemetry that were not followed, \
|
| 141 |
+
and why they were set aside]
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
## Section 4: Remediation
|
| 147 |
+
|
| 148 |
+
For each corrective action, identify which step in the causal chain it \
|
| 149 |
+
targets and what class of fix it is:
|
| 150 |
+
|
| 151 |
+
- **Root cause fix**: eliminates the condition that started the chain
|
| 152 |
+
- **Propagation fix**: limits blast radius if the root cause recurs
|
| 153 |
+
- **Detection fix**: reduces time-to-detect or time-to-mitigate
|
| 154 |
+
|
| 155 |
+
List actions from root cause outward. Prefer fixes that prevent recurrence \
|
| 156 |
+
over fixes that only improve response.
|
| 157 |
+
|
| 158 |
+
Output format:
|
| 159 |
+
|
| 160 |
+
| Action | Targets | Type |
|
| 161 |
+
|--------|---------|------|
|
| 162 |
+
| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix |
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
SOLUTION_PROMPT_TEMPLATE = """\
|
| 166 |
+
You are an expert site reliability engineer. You are given a ground-truth \
|
| 167 |
+
rubric describing an incident's root cause, mechanism, and telemetry evidence.
|
| 168 |
+
|
| 169 |
+
Your task: write an incident report as if you investigated this incident \
|
| 170 |
+
yourself. Use the rubric evidence to populate each section. Do NOT mention \
|
| 171 |
+
the rubric or that you were given ground-truth data — write as though you \
|
| 172 |
+
discovered everything through telemetry analysis.
|
| 173 |
+
|
| 174 |
+
## Ground-Truth Rubric
|
| 175 |
+
|
| 176 |
+
{rubric}
|
| 177 |
+
|
| 178 |
+
## Report Format
|
| 179 |
+
|
| 180 |
+
{report_format}
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def build_solution_prompt(rubric_md: str) -> str:
|
| 185 |
+
"""Build the LLM prompt from a formatted rubric markdown string."""
|
| 186 |
+
return SOLUTION_PROMPT_TEMPLATE.format(
|
| 187 |
+
rubric=rubric_md,
|
| 188 |
+
report_format=REPORT_FORMAT,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
async def generate_report(
|
| 193 |
+
client: Any,
|
| 194 |
+
rubric_data: dict,
|
| 195 |
+
model: str | None = DEFAULT_MODEL,
|
| 196 |
+
effort: str | None = DEFAULT_EFFORT,
|
| 197 |
+
) -> tuple[str, str, list[dict] | None]:
|
| 198 |
+
"""Generate an incident report from rubric JSON.
|
| 199 |
+
|
| 200 |
+
If ``model`` is ``None``, the formatted rubric is returned directly with
|
| 201 |
+
no LLM call. Otherwise the rubric is passed to the LLM to be reformatted
|
| 202 |
+
into an incident report.
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
A tuple of (report_text, prompt, reasoning_summary). When ``model``
|
| 206 |
+
is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``.
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
rubric_md = format_rubric(rubric_data)
|
| 210 |
+
if model is None:
|
| 211 |
+
return rubric_md, "", None
|
| 212 |
+
prompt = build_solution_prompt(rubric_md)
|
| 213 |
+
response_text, reasoning_summary = await async_call_llm_judge(
|
| 214 |
+
client, prompt, model=model, reasoning_effort=effort
|
| 215 |
+
)
|
| 216 |
+
return response_text, prompt, reasoning_summary
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
async def async_main() -> None:
|
| 220 |
+
"""CLI entry point: read rubric, call LLM, write report."""
|
| 221 |
+
parser = argparse.ArgumentParser(
|
| 222 |
+
description="Generate an incident report from a rubric JSON via LLM."
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--rubric",
|
| 226 |
+
type=str,
|
| 227 |
+
default="/tests/rubric.json",
|
| 228 |
+
help="Path to rubric JSON file.",
|
| 229 |
+
)
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--output",
|
| 232 |
+
type=str,
|
| 233 |
+
default="/app/report.md",
|
| 234 |
+
help="Path to write the generated report.",
|
| 235 |
+
)
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--model",
|
| 238 |
+
"-m",
|
| 239 |
+
type=str,
|
| 240 |
+
default=DEFAULT_MODEL,
|
| 241 |
+
help=(
|
| 242 |
+
"LLM model name. If omitted, the formatted rubric is written "
|
| 243 |
+
"directly as the report with no LLM call."
|
| 244 |
+
),
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--effort",
|
| 248 |
+
"-e",
|
| 249 |
+
type=str,
|
| 250 |
+
choices=["low", "medium", "high"],
|
| 251 |
+
default=DEFAULT_EFFORT,
|
| 252 |
+
help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).",
|
| 253 |
+
)
|
| 254 |
+
args = parser.parse_args()
|
| 255 |
+
|
| 256 |
+
logging.basicConfig(
|
| 257 |
+
level=logging.INFO,
|
| 258 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
rubric_path = Path(args.rubric)
|
| 262 |
+
output_path = Path(args.output)
|
| 263 |
+
|
| 264 |
+
if not rubric_path.is_file():
|
| 265 |
+
logger.warning(f"Rubric file not found: {rubric_path}; writing empty report")
|
| 266 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 267 |
+
output_path.write_text("")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
rubric_data = json.loads(rubric_path.read_text())
|
| 271 |
+
logger.info(
|
| 272 |
+
f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} "
|
| 273 |
+
f"from {rubric_path}"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
client: Any = None
|
| 277 |
+
if args.model is not None:
|
| 278 |
+
from openai import AsyncOpenAI
|
| 279 |
+
|
| 280 |
+
client = AsyncOpenAI(
|
| 281 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 282 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
report_text, _prompt, reasoning_summary = await generate_report(
|
| 286 |
+
client, rubric_data, model=args.model, effort=args.effort
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 290 |
+
output_path.write_text(report_text)
|
| 291 |
+
logger.info(f"Wrote report to {output_path}")
|
| 292 |
+
|
| 293 |
+
if reasoning_summary:
|
| 294 |
+
logger.info(f"Reasoning summary: {reasoning_summary}")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
if __name__ == "__main__":
|
| 298 |
+
asyncio.run(async_main())
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# ── Wait for the entrypoint to finish setting up the environment ──
|
| 5 |
+
echo "[solve] Waiting for environment to be ready..."
|
| 6 |
+
for i in $(seq 1 180); do
|
| 7 |
+
[ -f /tmp/env-ready ] && break
|
| 8 |
+
sleep 1
|
| 9 |
+
done
|
| 10 |
+
if [ ! -f /tmp/env-ready ]; then
|
| 11 |
+
echo "[solve] ERROR: Environment did not become ready within 180s" >&2
|
| 12 |
+
exit 1
|
| 13 |
+
fi
|
| 14 |
+
echo "[solve] Environment is ready."
|
| 15 |
+
|
| 16 |
+
# ── Verify all services are healthy ──
|
| 17 |
+
echo "[solve] Running health checks..."
|
| 18 |
+
source /tmp/env-ports
|
| 19 |
+
/app/check_health.sh || {
|
| 20 |
+
echo "[solve] ERROR: Health checks failed" >&2
|
| 21 |
+
exit 1
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# ── Generate solution report via LLM ──
|
| 25 |
+
echo "[solve] Installing dependencies..."
|
| 26 |
+
pip install tabulate
|
| 27 |
+
echo "[solve] Generating report..."
|
| 28 |
+
python /solution/solve.py --rubric /solution/rubric.json
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/expected.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"events": [
|
| 3 |
+
{
|
| 4 |
+
"event_id": "d1-i1-imageSlowLoad-on",
|
| 5 |
+
"root_cause": "imageSlowLoad",
|
| 6 |
+
"event_time": "2026-04-19T14:01:51.404464+00:00"
|
| 7 |
+
}
|
| 8 |
+
]
|
| 9 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/test.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
set +e
|
| 5 |
+
python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt
|
| 6 |
+
status=${PIPESTATUS[0]}
|
| 7 |
+
set -e
|
| 8 |
+
|
| 9 |
+
# Preserve agent predictions even on verifier failure (Harbor deletes containers).
|
| 10 |
+
if [[ -f /app/report.md ]]; then
|
| 11 |
+
mkdir -p /logs/verifier
|
| 12 |
+
cp /app/report.md /logs/verifier/report.md 2>/dev/null || true
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
if [[ -f /app/task_meta.json ]]; then
|
| 16 |
+
cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
exit $status
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
FROM ag2435/sre-otel-snapshot:{code_tag}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
build:
|
| 4 |
+
context: ${CONTEXT_DIR}
|
| 5 |
+
pull: true
|
| 6 |
+
image: ${MAIN_IMAGE_NAME}
|
| 7 |
+
command: [ "sh", "-c", "sleep infinity" ]
|
| 8 |
+
privileged: true
|
| 9 |
+
environment:
|
| 10 |
+
- TEST_DIR=${TEST_DIR}
|
| 11 |
+
- CONTEXT_DIR=${CONTEXT_DIR}
|
| 12 |
+
volumes:
|
| 13 |
+
- /var/run/docker.sock:/var/run/docker.sock
|
| 14 |
+
- ${CONTEXT_DIR}:${CONTEXT_DIR}
|
| 15 |
+
- ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH}
|
| 16 |
+
- ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH}
|
| 17 |
+
deploy:
|
| 18 |
+
resources:
|
| 19 |
+
limits:
|
| 20 |
+
cpus: ${CPUS}
|
| 21 |
+
memory: ${MEMORY}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py
ADDED
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate an incident report from a rubric JSON via LLM.
|
| 3 |
+
|
| 4 |
+
Standalone script designed to run inside a Harbor task container.
|
| 5 |
+
Also importable by ``run_solve.py`` for local batch generation.
|
| 6 |
+
|
| 7 |
+
Examples::
|
| 8 |
+
|
| 9 |
+
# Inside Harbor container (solve.sh calls this):
|
| 10 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md
|
| 11 |
+
|
| 12 |
+
# With custom model/effort:
|
| 13 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import asyncio
|
| 18 |
+
import json
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from check_prediction import async_call_llm_judge, format_rubric
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
DEFAULT_MODEL: str | None = None
|
| 29 |
+
DEFAULT_EFFORT = "high"
|
| 30 |
+
|
| 31 |
+
# Report format from harbor-template/instruction.md.template — sections 1-4.
|
| 32 |
+
REPORT_FORMAT = """\
|
| 33 |
+
Write a structured incident report with four sections: Summary, Timeline, \
|
| 34 |
+
5 Whys, and Remediation. Follow all section-specific rules below.
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
## Section 1: Summary
|
| 39 |
+
|
| 40 |
+
2-3 sentences describing what happened, when, and the high-level impact. \
|
| 41 |
+
This should be understandable by someone unfamiliar with the system. Focus \
|
| 42 |
+
on what DID happen and the observable impact — mention request failures if \
|
| 43 |
+
they occurred, but do NOT mention the absence of failures or errors as this \
|
| 44 |
+
can be misread and cause confusion. You may name the root cause in a single \
|
| 45 |
+
phrase (e.g. "due to a misconfigured batch job") but do not explain the \
|
| 46 |
+
causal chain — that belongs in the 5 Whys section.
|
| 47 |
+
|
| 48 |
+
Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \
|
| 49 |
+
503 errors for 14% of checkout requests, affecting paying users, due to a \
|
| 50 |
+
Redis cache eviction. The full causal chain is detailed in the 5 Whys section \
|
| 51 |
+
below."
|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
## Section 2: Timeline
|
| 56 |
+
|
| 57 |
+
A chronological narrative of ONLY what went wrong, reconstructed from the \
|
| 58 |
+
provided telemetry. Each entry should be a single succinct line. Cover \
|
| 59 |
+
higher-level events — when a change was introduced, when symptoms started, \
|
| 60 |
+
when a change was reverted, when symptoms subsided — not individual error \
|
| 61 |
+
occurrences. The first entry should be the earliest anomaly visible in the \
|
| 62 |
+
provided telemetry; this establishes the incident start time referenced by \
|
| 63 |
+
the Summary and 5 Whys sections.
|
| 64 |
+
|
| 65 |
+
For each entry:
|
| 66 |
+
- State the time (UTC), the service(s) involved, and what happened
|
| 67 |
+
- Quantify where possible (error rate, duration, number of affected requests)
|
| 68 |
+
- Do NOT include normal/healthy behavior, baseline noise, or things that \
|
| 69 |
+
worked correctly
|
| 70 |
+
|
| 71 |
+
Example format:
|
| 72 |
+
```
|
| 73 |
+
09:44 UTC — analytics-job deployed with no memory limit set
|
| 74 |
+
14:17 UTC — redis-cache-0 OOMKilled; node memory at 97%
|
| 75 |
+
14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres
|
| 76 |
+
14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14%
|
| 77 |
+
14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
---
|
| 81 |
+
|
| 82 |
+
## Section 3: 5 Whys
|
| 83 |
+
|
| 84 |
+
Rules:
|
| 85 |
+
1. Start by stating the problem as a precise, observable symptom — not a \
|
| 86 |
+
cause. Include what failed, when, and impact (error rate, affected users, \
|
| 87 |
+
duration).
|
| 88 |
+
2. Each "why" answer must be grounded in the provided telemetry. Cite only \
|
| 89 |
+
the telemetry types relevant to that step, using the format below for each.
|
| 90 |
+
|
| 91 |
+
- Metrics: one sentence describing the baseline value (or typical range), \
|
| 92 |
+
what it changed to, and at what UTC timestamp. Where relevant, include rate \
|
| 93 |
+
of change or duration. Follow with the exact PromQL query that would surface it.
|
| 94 |
+
Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \
|
| 95 |
+
14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\
|
| 96 |
+
status=~"5.."}[1m])"
|
| 97 |
+
|
| 98 |
+
- Traces: the cascade from the highest-level operation down to the deepest \
|
| 99 |
+
failing span, followed by representative trace IDs from the provided data.
|
| 100 |
+
Example — "checkout request → order-svc goroutine exhaustion → \
|
| 101 |
+
inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736"
|
| 102 |
+
|
| 103 |
+
- Logs: one sentence with service, endpoint, error, and time range, \
|
| 104 |
+
followed by the exact Lucene query that would retrieve the relevant log lines.
|
| 105 |
+
Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \
|
| 106 |
+
returned 503s. Lucene: service:order-svc AND status:503 AND \
|
| 107 |
+
endpoint:\\"/api/checkout\\""
|
| 108 |
+
3. Each "why" targets the previous answer, not the original problem. Drill \
|
| 109 |
+
down one causal chain; do not branch.
|
| 110 |
+
4. Never accept "human error" or "operator mistake" as a terminal answer. \
|
| 111 |
+
Ask why the human was in a position to make that error.
|
| 112 |
+
5. Stop when you reach a cause that is: (a) actionable — something a team \
|
| 113 |
+
can change, or (b) a process or system gap that allowed the failure to \
|
| 114 |
+
propagate. The number of steps is not fixed at 5.
|
| 115 |
+
6. Only include steps that are directly supported by the provided telemetry. \
|
| 116 |
+
If the causal chain cannot be completed with the available evidence, stop \
|
| 117 |
+
and note what additional telemetry would be needed to continue.
|
| 118 |
+
7. After the chain, note any branches you did NOT follow. If the incident \
|
| 119 |
+
has multiple contributing causes that cannot fit a single chain, say so \
|
| 120 |
+
explicitly rather than forcing one.
|
| 121 |
+
|
| 122 |
+
Output format:
|
| 123 |
+
|
| 124 |
+
```
|
| 125 |
+
Problem statement:
|
| 126 |
+
[Observable symptom with time, impact, and detection method]
|
| 127 |
+
|
| 128 |
+
Why 1: [question] → [answer]
|
| 129 |
+
Evidence: [specific signal]
|
| 130 |
+
|
| 131 |
+
Why 2: [question] → [answer]
|
| 132 |
+
Evidence: [specific signal]
|
| 133 |
+
|
| 134 |
+
...
|
| 135 |
+
|
| 136 |
+
Root cause:
|
| 137 |
+
[Single sentence naming the systemic or process failure]
|
| 138 |
+
|
| 139 |
+
Unexplored branches:
|
| 140 |
+
[Contributing factors visible in telemetry that were not followed, \
|
| 141 |
+
and why they were set aside]
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
## Section 4: Remediation
|
| 147 |
+
|
| 148 |
+
For each corrective action, identify which step in the causal chain it \
|
| 149 |
+
targets and what class of fix it is:
|
| 150 |
+
|
| 151 |
+
- **Root cause fix**: eliminates the condition that started the chain
|
| 152 |
+
- **Propagation fix**: limits blast radius if the root cause recurs
|
| 153 |
+
- **Detection fix**: reduces time-to-detect or time-to-mitigate
|
| 154 |
+
|
| 155 |
+
List actions from root cause outward. Prefer fixes that prevent recurrence \
|
| 156 |
+
over fixes that only improve response.
|
| 157 |
+
|
| 158 |
+
Output format:
|
| 159 |
+
|
| 160 |
+
| Action | Targets | Type |
|
| 161 |
+
|--------|---------|------|
|
| 162 |
+
| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix |
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
SOLUTION_PROMPT_TEMPLATE = """\
|
| 166 |
+
You are an expert site reliability engineer. You are given a ground-truth \
|
| 167 |
+
rubric describing an incident's root cause, mechanism, and telemetry evidence.
|
| 168 |
+
|
| 169 |
+
Your task: write an incident report as if you investigated this incident \
|
| 170 |
+
yourself. Use the rubric evidence to populate each section. Do NOT mention \
|
| 171 |
+
the rubric or that you were given ground-truth data — write as though you \
|
| 172 |
+
discovered everything through telemetry analysis.
|
| 173 |
+
|
| 174 |
+
## Ground-Truth Rubric
|
| 175 |
+
|
| 176 |
+
{rubric}
|
| 177 |
+
|
| 178 |
+
## Report Format
|
| 179 |
+
|
| 180 |
+
{report_format}
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def build_solution_prompt(rubric_md: str) -> str:
|
| 185 |
+
"""Build the LLM prompt from a formatted rubric markdown string."""
|
| 186 |
+
return SOLUTION_PROMPT_TEMPLATE.format(
|
| 187 |
+
rubric=rubric_md,
|
| 188 |
+
report_format=REPORT_FORMAT,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
async def generate_report(
|
| 193 |
+
client: Any,
|
| 194 |
+
rubric_data: dict,
|
| 195 |
+
model: str | None = DEFAULT_MODEL,
|
| 196 |
+
effort: str | None = DEFAULT_EFFORT,
|
| 197 |
+
) -> tuple[str, str, list[dict] | None]:
|
| 198 |
+
"""Generate an incident report from rubric JSON.
|
| 199 |
+
|
| 200 |
+
If ``model`` is ``None``, the formatted rubric is returned directly with
|
| 201 |
+
no LLM call. Otherwise the rubric is passed to the LLM to be reformatted
|
| 202 |
+
into an incident report.
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
A tuple of (report_text, prompt, reasoning_summary). When ``model``
|
| 206 |
+
is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``.
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
rubric_md = format_rubric(rubric_data)
|
| 210 |
+
if model is None:
|
| 211 |
+
return rubric_md, "", None
|
| 212 |
+
prompt = build_solution_prompt(rubric_md)
|
| 213 |
+
response_text, reasoning_summary = await async_call_llm_judge(
|
| 214 |
+
client, prompt, model=model, reasoning_effort=effort
|
| 215 |
+
)
|
| 216 |
+
return response_text, prompt, reasoning_summary
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
async def async_main() -> None:
|
| 220 |
+
"""CLI entry point: read rubric, call LLM, write report."""
|
| 221 |
+
parser = argparse.ArgumentParser(
|
| 222 |
+
description="Generate an incident report from a rubric JSON via LLM."
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--rubric",
|
| 226 |
+
type=str,
|
| 227 |
+
default="/tests/rubric.json",
|
| 228 |
+
help="Path to rubric JSON file.",
|
| 229 |
+
)
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--output",
|
| 232 |
+
type=str,
|
| 233 |
+
default="/app/report.md",
|
| 234 |
+
help="Path to write the generated report.",
|
| 235 |
+
)
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--model",
|
| 238 |
+
"-m",
|
| 239 |
+
type=str,
|
| 240 |
+
default=DEFAULT_MODEL,
|
| 241 |
+
help=(
|
| 242 |
+
"LLM model name. If omitted, the formatted rubric is written "
|
| 243 |
+
"directly as the report with no LLM call."
|
| 244 |
+
),
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--effort",
|
| 248 |
+
"-e",
|
| 249 |
+
type=str,
|
| 250 |
+
choices=["low", "medium", "high"],
|
| 251 |
+
default=DEFAULT_EFFORT,
|
| 252 |
+
help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).",
|
| 253 |
+
)
|
| 254 |
+
args = parser.parse_args()
|
| 255 |
+
|
| 256 |
+
logging.basicConfig(
|
| 257 |
+
level=logging.INFO,
|
| 258 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
rubric_path = Path(args.rubric)
|
| 262 |
+
output_path = Path(args.output)
|
| 263 |
+
|
| 264 |
+
if not rubric_path.is_file():
|
| 265 |
+
logger.warning(f"Rubric file not found: {rubric_path}; writing empty report")
|
| 266 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 267 |
+
output_path.write_text("")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
rubric_data = json.loads(rubric_path.read_text())
|
| 271 |
+
logger.info(
|
| 272 |
+
f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} "
|
| 273 |
+
f"from {rubric_path}"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
client: Any = None
|
| 277 |
+
if args.model is not None:
|
| 278 |
+
from openai import AsyncOpenAI
|
| 279 |
+
|
| 280 |
+
client = AsyncOpenAI(
|
| 281 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 282 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
report_text, _prompt, reasoning_summary = await generate_report(
|
| 286 |
+
client, rubric_data, model=args.model, effort=args.effort
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 290 |
+
output_path.write_text(report_text)
|
| 291 |
+
logger.info(f"Wrote report to {output_path}")
|
| 292 |
+
|
| 293 |
+
if reasoning_summary:
|
| 294 |
+
logger.info(f"Reasoning summary: {reasoning_summary}")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
if __name__ == "__main__":
|
| 298 |
+
asyncio.run(async_main())
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# ── Wait for the entrypoint to finish setting up the environment ──
|
| 5 |
+
echo "[solve] Waiting for environment to be ready..."
|
| 6 |
+
for i in $(seq 1 180); do
|
| 7 |
+
[ -f /tmp/env-ready ] && break
|
| 8 |
+
sleep 1
|
| 9 |
+
done
|
| 10 |
+
if [ ! -f /tmp/env-ready ]; then
|
| 11 |
+
echo "[solve] ERROR: Environment did not become ready within 180s" >&2
|
| 12 |
+
exit 1
|
| 13 |
+
fi
|
| 14 |
+
echo "[solve] Environment is ready."
|
| 15 |
+
|
| 16 |
+
# ── Verify all services are healthy ──
|
| 17 |
+
echo "[solve] Running health checks..."
|
| 18 |
+
source /tmp/env-ports
|
| 19 |
+
/app/check_health.sh || {
|
| 20 |
+
echo "[solve] ERROR: Health checks failed" >&2
|
| 21 |
+
exit 1
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# ── Generate solution report via LLM ──
|
| 25 |
+
echo "[solve] Installing dependencies..."
|
| 26 |
+
pip install tabulate
|
| 27 |
+
echo "[solve] Generating report..."
|
| 28 |
+
python /solution/solve.py --rubric /solution/rubric.json
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"events": [
|
| 3 |
+
{
|
| 4 |
+
"event_id": "d1-i1-imageSlowLoad-on",
|
| 5 |
+
"root_cause": "imageSlowLoad",
|
| 6 |
+
"event_time": "2026-04-19T14:01:51.404464+00:00"
|
| 7 |
+
}
|
| 8 |
+
]
|
| 9 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
set +e
|
| 5 |
+
python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt
|
| 6 |
+
status=${PIPESTATUS[0]}
|
| 7 |
+
set -e
|
| 8 |
+
|
| 9 |
+
# Preserve agent predictions even on verifier failure (Harbor deletes containers).
|
| 10 |
+
if [[ -f /app/report.md ]]; then
|
| 11 |
+
mkdir -p /logs/verifier
|
| 12 |
+
cp /app/report.md /logs/verifier/report.md 2>/dev/null || true
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
if [[ -f /app/task_meta.json ]]; then
|
| 16 |
+
cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
exit $status
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
FROM ag2435/sre-otel-snapshot:{code_tag}
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
build:
|
| 4 |
+
context: ${CONTEXT_DIR}
|
| 5 |
+
pull: true
|
| 6 |
+
image: ${MAIN_IMAGE_NAME}
|
| 7 |
+
command: [ "sh", "-c", "sleep infinity" ]
|
| 8 |
+
privileged: true
|
| 9 |
+
environment:
|
| 10 |
+
- TEST_DIR=${TEST_DIR}
|
| 11 |
+
- CONTEXT_DIR=${CONTEXT_DIR}
|
| 12 |
+
volumes:
|
| 13 |
+
- /var/run/docker.sock:/var/run/docker.sock
|
| 14 |
+
- ${CONTEXT_DIR}:${CONTEXT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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate an incident report from a rubric JSON via LLM.
|
| 3 |
+
|
| 4 |
+
Standalone script designed to run inside a Harbor task container.
|
| 5 |
+
Also importable by ``run_solve.py`` for local batch generation.
|
| 6 |
+
|
| 7 |
+
Examples::
|
| 8 |
+
|
| 9 |
+
# Inside Harbor container (solve.sh calls this):
|
| 10 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md
|
| 11 |
+
|
| 12 |
+
# With custom model/effort:
|
| 13 |
+
python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import asyncio
|
| 18 |
+
import json
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from check_prediction import async_call_llm_judge, format_rubric
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
DEFAULT_MODEL: str | None = None
|
| 29 |
+
DEFAULT_EFFORT = "high"
|
| 30 |
+
|
| 31 |
+
# Report format from harbor-template/instruction.md.template — sections 1-4.
|
| 32 |
+
REPORT_FORMAT = """\
|
| 33 |
+
Write a structured incident report with four sections: Summary, Timeline, \
|
| 34 |
+
5 Whys, and Remediation. Follow all section-specific rules below.
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
## Section 1: Summary
|
| 39 |
+
|
| 40 |
+
2-3 sentences describing what happened, when, and the high-level impact. \
|
| 41 |
+
This should be understandable by someone unfamiliar with the system. Focus \
|
| 42 |
+
on what DID happen and the observable impact — mention request failures if \
|
| 43 |
+
they occurred, but do NOT mention the absence of failures or errors as this \
|
| 44 |
+
can be misread and cause confusion. You may name the root cause in a single \
|
| 45 |
+
phrase (e.g. "due to a misconfigured batch job") but do not explain the \
|
| 46 |
+
causal chain — that belongs in the 5 Whys section.
|
| 47 |
+
|
| 48 |
+
Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \
|
| 49 |
+
503 errors for 14% of checkout requests, affecting paying users, due to a \
|
| 50 |
+
Redis cache eviction. The full causal chain is detailed in the 5 Whys section \
|
| 51 |
+
below."
|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
## Section 2: Timeline
|
| 56 |
+
|
| 57 |
+
A chronological narrative of ONLY what went wrong, reconstructed from the \
|
| 58 |
+
provided telemetry. Each entry should be a single succinct line. Cover \
|
| 59 |
+
higher-level events — when a change was introduced, when symptoms started, \
|
| 60 |
+
when a change was reverted, when symptoms subsided — not individual error \
|
| 61 |
+
occurrences. The first entry should be the earliest anomaly visible in the \
|
| 62 |
+
provided telemetry; this establishes the incident start time referenced by \
|
| 63 |
+
the Summary and 5 Whys sections.
|
| 64 |
+
|
| 65 |
+
For each entry:
|
| 66 |
+
- State the time (UTC), the service(s) involved, and what happened
|
| 67 |
+
- Quantify where possible (error rate, duration, number of affected requests)
|
| 68 |
+
- Do NOT include normal/healthy behavior, baseline noise, or things that \
|
| 69 |
+
worked correctly
|
| 70 |
+
|
| 71 |
+
Example format:
|
| 72 |
+
```
|
| 73 |
+
09:44 UTC — analytics-job deployed with no memory limit set
|
| 74 |
+
14:17 UTC — redis-cache-0 OOMKilled; node memory at 97%
|
| 75 |
+
14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres
|
| 76 |
+
14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14%
|
| 77 |
+
14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
---
|
| 81 |
+
|
| 82 |
+
## Section 3: 5 Whys
|
| 83 |
+
|
| 84 |
+
Rules:
|
| 85 |
+
1. Start by stating the problem as a precise, observable symptom — not a \
|
| 86 |
+
cause. Include what failed, when, and impact (error rate, affected users, \
|
| 87 |
+
duration).
|
| 88 |
+
2. Each "why" answer must be grounded in the provided telemetry. Cite only \
|
| 89 |
+
the telemetry types relevant to that step, using the format below for each.
|
| 90 |
+
|
| 91 |
+
- Metrics: one sentence describing the baseline value (or typical range), \
|
| 92 |
+
what it changed to, and at what UTC timestamp. Where relevant, include rate \
|
| 93 |
+
of change or duration. Follow with the exact PromQL query that would surface it.
|
| 94 |
+
Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \
|
| 95 |
+
14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\
|
| 96 |
+
status=~"5.."}[1m])"
|
| 97 |
+
|
| 98 |
+
- Traces: the cascade from the highest-level operation down to the deepest \
|
| 99 |
+
failing span, followed by representative trace IDs from the provided data.
|
| 100 |
+
Example — "checkout request → order-svc goroutine exhaustion → \
|
| 101 |
+
inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736"
|
| 102 |
+
|
| 103 |
+
- Logs: one sentence with service, endpoint, error, and time range, \
|
| 104 |
+
followed by the exact Lucene query that would retrieve the relevant log lines.
|
| 105 |
+
Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \
|
| 106 |
+
returned 503s. Lucene: service:order-svc AND status:503 AND \
|
| 107 |
+
endpoint:\\"/api/checkout\\""
|
| 108 |
+
3. Each "why" targets the previous answer, not the original problem. Drill \
|
| 109 |
+
down one causal chain; do not branch.
|
| 110 |
+
4. Never accept "human error" or "operator mistake" as a terminal answer. \
|
| 111 |
+
Ask why the human was in a position to make that error.
|
| 112 |
+
5. Stop when you reach a cause that is: (a) actionable — something a team \
|
| 113 |
+
can change, or (b) a process or system gap that allowed the failure to \
|
| 114 |
+
propagate. The number of steps is not fixed at 5.
|
| 115 |
+
6. Only include steps that are directly supported by the provided telemetry. \
|
| 116 |
+
If the causal chain cannot be completed with the available evidence, stop \
|
| 117 |
+
and note what additional telemetry would be needed to continue.
|
| 118 |
+
7. After the chain, note any branches you did NOT follow. If the incident \
|
| 119 |
+
has multiple contributing causes that cannot fit a single chain, say so \
|
| 120 |
+
explicitly rather than forcing one.
|
| 121 |
+
|
| 122 |
+
Output format:
|
| 123 |
+
|
| 124 |
+
```
|
| 125 |
+
Problem statement:
|
| 126 |
+
[Observable symptom with time, impact, and detection method]
|
| 127 |
+
|
| 128 |
+
Why 1: [question] → [answer]
|
| 129 |
+
Evidence: [specific signal]
|
| 130 |
+
|
| 131 |
+
Why 2: [question] → [answer]
|
| 132 |
+
Evidence: [specific signal]
|
| 133 |
+
|
| 134 |
+
...
|
| 135 |
+
|
| 136 |
+
Root cause:
|
| 137 |
+
[Single sentence naming the systemic or process failure]
|
| 138 |
+
|
| 139 |
+
Unexplored branches:
|
| 140 |
+
[Contributing factors visible in telemetry that were not followed, \
|
| 141 |
+
and why they were set aside]
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
## Section 4: Remediation
|
| 147 |
+
|
| 148 |
+
For each corrective action, identify which step in the causal chain it \
|
| 149 |
+
targets and what class of fix it is:
|
| 150 |
+
|
| 151 |
+
- **Root cause fix**: eliminates the condition that started the chain
|
| 152 |
+
- **Propagation fix**: limits blast radius if the root cause recurs
|
| 153 |
+
- **Detection fix**: reduces time-to-detect or time-to-mitigate
|
| 154 |
+
|
| 155 |
+
List actions from root cause outward. Prefer fixes that prevent recurrence \
|
| 156 |
+
over fixes that only improve response.
|
| 157 |
+
|
| 158 |
+
Output format:
|
| 159 |
+
|
| 160 |
+
| Action | Targets | Type |
|
| 161 |
+
|--------|---------|------|
|
| 162 |
+
| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix |
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
SOLUTION_PROMPT_TEMPLATE = """\
|
| 166 |
+
You are an expert site reliability engineer. You are given a ground-truth \
|
| 167 |
+
rubric describing an incident's root cause, mechanism, and telemetry evidence.
|
| 168 |
+
|
| 169 |
+
Your task: write an incident report as if you investigated this incident \
|
| 170 |
+
yourself. Use the rubric evidence to populate each section. Do NOT mention \
|
| 171 |
+
the rubric or that you were given ground-truth data — write as though you \
|
| 172 |
+
discovered everything through telemetry analysis.
|
| 173 |
+
|
| 174 |
+
## Ground-Truth Rubric
|
| 175 |
+
|
| 176 |
+
{rubric}
|
| 177 |
+
|
| 178 |
+
## Report Format
|
| 179 |
+
|
| 180 |
+
{report_format}
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def build_solution_prompt(rubric_md: str) -> str:
|
| 185 |
+
"""Build the LLM prompt from a formatted rubric markdown string."""
|
| 186 |
+
return SOLUTION_PROMPT_TEMPLATE.format(
|
| 187 |
+
rubric=rubric_md,
|
| 188 |
+
report_format=REPORT_FORMAT,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
async def generate_report(
|
| 193 |
+
client: Any,
|
| 194 |
+
rubric_data: dict,
|
| 195 |
+
model: str | None = DEFAULT_MODEL,
|
| 196 |
+
effort: str | None = DEFAULT_EFFORT,
|
| 197 |
+
) -> tuple[str, str, list[dict] | None]:
|
| 198 |
+
"""Generate an incident report from rubric JSON.
|
| 199 |
+
|
| 200 |
+
If ``model`` is ``None``, the formatted rubric is returned directly with
|
| 201 |
+
no LLM call. Otherwise the rubric is passed to the LLM to be reformatted
|
| 202 |
+
into an incident report.
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
A tuple of (report_text, prompt, reasoning_summary). When ``model``
|
| 206 |
+
is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``.
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
rubric_md = format_rubric(rubric_data)
|
| 210 |
+
if model is None:
|
| 211 |
+
return rubric_md, "", None
|
| 212 |
+
prompt = build_solution_prompt(rubric_md)
|
| 213 |
+
response_text, reasoning_summary = await async_call_llm_judge(
|
| 214 |
+
client, prompt, model=model, reasoning_effort=effort
|
| 215 |
+
)
|
| 216 |
+
return response_text, prompt, reasoning_summary
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
async def async_main() -> None:
|
| 220 |
+
"""CLI entry point: read rubric, call LLM, write report."""
|
| 221 |
+
parser = argparse.ArgumentParser(
|
| 222 |
+
description="Generate an incident report from a rubric JSON via LLM."
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--rubric",
|
| 226 |
+
type=str,
|
| 227 |
+
default="/tests/rubric.json",
|
| 228 |
+
help="Path to rubric JSON file.",
|
| 229 |
+
)
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--output",
|
| 232 |
+
type=str,
|
| 233 |
+
default="/app/report.md",
|
| 234 |
+
help="Path to write the generated report.",
|
| 235 |
+
)
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--model",
|
| 238 |
+
"-m",
|
| 239 |
+
type=str,
|
| 240 |
+
default=DEFAULT_MODEL,
|
| 241 |
+
help=(
|
| 242 |
+
"LLM model name. If omitted, the formatted rubric is written "
|
| 243 |
+
"directly as the report with no LLM call."
|
| 244 |
+
),
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--effort",
|
| 248 |
+
"-e",
|
| 249 |
+
type=str,
|
| 250 |
+
choices=["low", "medium", "high"],
|
| 251 |
+
default=DEFAULT_EFFORT,
|
| 252 |
+
help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).",
|
| 253 |
+
)
|
| 254 |
+
args = parser.parse_args()
|
| 255 |
+
|
| 256 |
+
logging.basicConfig(
|
| 257 |
+
level=logging.INFO,
|
| 258 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
rubric_path = Path(args.rubric)
|
| 262 |
+
output_path = Path(args.output)
|
| 263 |
+
|
| 264 |
+
if not rubric_path.is_file():
|
| 265 |
+
logger.warning(f"Rubric file not found: {rubric_path}; writing empty report")
|
| 266 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 267 |
+
output_path.write_text("")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
rubric_data = json.loads(rubric_path.read_text())
|
| 271 |
+
logger.info(
|
| 272 |
+
f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} "
|
| 273 |
+
f"from {rubric_path}"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
client: Any = None
|
| 277 |
+
if args.model is not None:
|
| 278 |
+
from openai import AsyncOpenAI
|
| 279 |
+
|
| 280 |
+
client = AsyncOpenAI(
|
| 281 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 282 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
report_text, _prompt, reasoning_summary = await generate_report(
|
| 286 |
+
client, rubric_data, model=args.model, effort=args.effort
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 290 |
+
output_path.write_text(report_text)
|
| 291 |
+
logger.info(f"Wrote report to {output_path}")
|
| 292 |
+
|
| 293 |
+
if reasoning_summary:
|
| 294 |
+
logger.info(f"Reasoning summary: {reasoning_summary}")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
if __name__ == "__main__":
|
| 298 |
+
asyncio.run(async_main())
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# ── Wait for the entrypoint to finish setting up the environment ──
|
| 5 |
+
echo "[solve] Waiting for environment to be ready..."
|
| 6 |
+
for i in $(seq 1 180); do
|
| 7 |
+
[ -f /tmp/env-ready ] && break
|
| 8 |
+
sleep 1
|
| 9 |
+
done
|
| 10 |
+
if [ ! -f /tmp/env-ready ]; then
|
| 11 |
+
echo "[solve] ERROR: Environment did not become ready within 180s" >&2
|
| 12 |
+
exit 1
|
| 13 |
+
fi
|
| 14 |
+
echo "[solve] Environment is ready."
|
| 15 |
+
|
| 16 |
+
# ── Verify all services are healthy ──
|
| 17 |
+
echo "[solve] Running health checks..."
|
| 18 |
+
source /tmp/env-ports
|
| 19 |
+
/app/check_health.sh || {
|
| 20 |
+
echo "[solve] ERROR: Health checks failed" >&2
|
| 21 |
+
exit 1
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# ── Generate solution report via LLM ──
|
| 25 |
+
echo "[solve] Installing dependencies..."
|
| 26 |
+
pip install tabulate
|
| 27 |
+
echo "[solve] Generating report..."
|
| 28 |
+
python /solution/solve.py --rubric /solution/rubric.json
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"events": [
|
| 3 |
+
{
|
| 4 |
+
"event_id": "d1-i1-imageSlowLoad-on",
|
| 5 |
+
"root_cause": "imageSlowLoad",
|
| 6 |
+
"event_time": "2026-04-19T14:01:51.404464+00:00"
|
| 7 |
+
}
|
| 8 |
+
]
|
| 9 |
+
}
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|
tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
set +e
|
| 5 |
+
python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt
|
| 6 |
+
status=${PIPESTATUS[0]}
|
| 7 |
+
set -e
|
| 8 |
+
|
| 9 |
+
# Preserve agent predictions even on verifier failure (Harbor deletes containers).
|
| 10 |
+
if [[ -f /app/report.md ]]; then
|
| 11 |
+
mkdir -p /logs/verifier
|
| 12 |
+
cp /app/report.md /logs/verifier/report.md 2>/dev/null || true
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
if [[ -f /app/task_meta.json ]]; then
|
| 16 |
+
cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
exit $status
|
tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
FROM ag2435/sre-otel-snapshot:{code_tag}
|
tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
build:
|
| 4 |
+
context: ${CONTEXT_DIR}
|
| 5 |
+
pull: true
|
| 6 |
+
image: ${MAIN_IMAGE_NAME}
|
| 7 |
+
command: [ "sh", "-c", "sleep infinity" ]
|
| 8 |
+
privileged: true
|
| 9 |
+
environment:
|
| 10 |
+
- TEST_DIR=${TEST_DIR}
|
| 11 |
+
- CONTEXT_DIR=${CONTEXT_DIR}
|
| 12 |
+
volumes:
|
| 13 |
+
- /var/run/docker.sock:/var/run/docker.sock
|
| 14 |
+
- ${CONTEXT_DIR}:${CONTEXT_DIR}
|
| 15 |
+
- ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH}
|
| 16 |
+
- ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH}
|
| 17 |
+
deploy:
|
| 18 |
+
resources:
|
| 19 |
+
limits:
|
| 20 |
+
cpus: ${CPUS}
|
| 21 |
+
memory: ${MEMORY}
|
tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks.
|
| 2 |
+
|
| 3 |
+
Supports two modes:
|
| 4 |
+
|
| 5 |
+
1. **Harbor verifier** (default):
|
| 6 |
+
python /tests/check_prediction.py
|
| 7 |
+
|
| 8 |
+
2. **Post-hoc single-trial**:
|
| 9 |
+
python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json]
|
| 10 |
+
|
| 11 |
+
Falls back to string-match scoring when OPENAI_API_KEY is not set.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import traceback
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from tabulate import tabulate
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
JUDGE_PROMPT_MULTI_HEADER = """\
|
| 29 |
+
You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report.
|
| 30 |
+
|
| 31 |
+
You are given:
|
| 32 |
+
1. **One or more** ground-truth rubrics. Each describes a plausible root cause, its incident time, mechanism, and symptoms. Several flags may have been active in the same window; the agent is credited if it correctly identifies **any one** of these rubrics.
|
| 33 |
+
2. The SRE agent's incident RCA report.
|
| 34 |
+
|
| 35 |
+
## SRE Agent's Incident RCA Report
|
| 36 |
+
|
| 37 |
+
{predictions}
|
| 38 |
+
|
| 39 |
+
## Ground-Truth Rubrics
|
| 40 |
+
|
| 41 |
+
{rubrics}
|
| 42 |
+
|
| 43 |
+
## Evaluation Questions
|
| 44 |
+
|
| 45 |
+
For **each rubric** in order, answer every question with true or false. Base your answer only on evidence in the agent's report; if the report does not cite the required evidence, answer false. The output must contain one entry per rubric, in the same order, and must preserve cluster order within each rubric exactly as listed.
|
| 46 |
+
|
| 47 |
+
For each rubric:
|
| 48 |
+
|
| 49 |
+
- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`?
|
| 50 |
+
- `feature_flag_match`: Did the agent identify this rubric's feature flag as a root cause? (The agent may name multiple flags; mark true if this flag is among them.)
|
| 51 |
+
- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure?
|
| 52 |
+
- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
JUDGE_PROMPT_SCORING_FOOTER = """\
|
| 56 |
+
|
| 57 |
+
## Overall Score
|
| 58 |
+
|
| 59 |
+
Score the incident RCA report on a scale of 0 to 3. The agent is credited if it correctly identifies **any one** of the listed rubrics — score against the rubric the agent's report best matches. Scoring is based on content correctness only; do not penalize or reward for formatting, prose style, or structural polish. Materially incorrect or misleading claims count against the score: if the report would otherwise score N but also adds a materially wrong claim (e.g., invents an unrelated additional cause), drop to N-1 (floor at 0). A report that correctly identifies one root cause but introduces a misleading fabrication alongside it therefore scores 2, not 3. When applying this penalty, explicitly identify in your reasoning which specific claim is materially wrong — quote or paraphrase the offending text. Do not apply the penalty without naming the offending claim; missing detail or incomplete explanation does not qualify as a materially wrong claim. Naming several of the listed plausible root causes is **not** a materially wrong claim.
|
| 60 |
+
|
| 61 |
+
- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause
|
| 62 |
+
- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further
|
| 63 |
+
- 2: AI makes correct progress beyond symptoms — the report identifies some of the ground-truth metrics, logs, or traces for at least one rubric and moves toward that root cause, but does not fully identify any single root cause
|
| 64 |
+
- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals
|
| 65 |
+
|
| 66 |
+
Respond with ONLY a JSON object matching the provided output schema.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DEFAULT_MODEL = "openai-gpt-5.4"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# Rubric rendering (JSON -> markdown)
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 78 |
+
"""Render log clusters as markdown subsections."""
|
| 79 |
+
for cluster in clusters:
|
| 80 |
+
name = cluster.get("name", "Unknown")
|
| 81 |
+
count = cluster.get("count")
|
| 82 |
+
suffix = f" ({count} entries)" if count is not None else ""
|
| 83 |
+
lines.append(f"#### {name}{suffix}")
|
| 84 |
+
lines.append("")
|
| 85 |
+
|
| 86 |
+
description = cluster.get("description", "")
|
| 87 |
+
if description:
|
| 88 |
+
lines.append(description)
|
| 89 |
+
lines.append("")
|
| 90 |
+
|
| 91 |
+
cause = cluster.get("cause", "")
|
| 92 |
+
if cause:
|
| 93 |
+
lines.append(f"**Cause:** {cause}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
|
| 96 |
+
source = cluster.get("source", "")
|
| 97 |
+
if source:
|
| 98 |
+
lines.append(f"**Source:** {source}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
|
| 101 |
+
attrs = cluster.get("representative_attributes", {})
|
| 102 |
+
if attrs:
|
| 103 |
+
lines.append("**Representative attributes:**")
|
| 104 |
+
lines.append("")
|
| 105 |
+
rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()]
|
| 106 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 107 |
+
lines.append("")
|
| 108 |
+
|
| 109 |
+
docs = cluster.get("log_documents", [])
|
| 110 |
+
if docs:
|
| 111 |
+
lines.append("**Log documents:**")
|
| 112 |
+
lines.append("")
|
| 113 |
+
rows = [
|
| 114 |
+
[f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs
|
| 115 |
+
]
|
| 116 |
+
lines.append(
|
| 117 |
+
tabulate(
|
| 118 |
+
rows, headers=["_index", "_id", "@timestamp"], tablefmt="github"
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
lines.append("")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None:
|
| 125 |
+
"""Render trace clusters as markdown subsections."""
|
| 126 |
+
for cluster in clusters:
|
| 127 |
+
name = cluster.get("name", "Unknown")
|
| 128 |
+
count = cluster.get("count")
|
| 129 |
+
suffix = f" ({count} traces)" if count is not None else ""
|
| 130 |
+
lines.append(f"#### {name}{suffix}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
|
| 133 |
+
description = cluster.get("description", "")
|
| 134 |
+
if description:
|
| 135 |
+
lines.append(description)
|
| 136 |
+
lines.append("")
|
| 137 |
+
|
| 138 |
+
cause = cluster.get("cause", "")
|
| 139 |
+
if cause:
|
| 140 |
+
lines.append(f"**Cause:** {cause}")
|
| 141 |
+
lines.append("")
|
| 142 |
+
|
| 143 |
+
call_chain = cluster.get("call_chain", "")
|
| 144 |
+
if call_chain:
|
| 145 |
+
lines.append("**Call chain:**")
|
| 146 |
+
lines.append("")
|
| 147 |
+
lines.append("```")
|
| 148 |
+
lines.append(call_chain)
|
| 149 |
+
lines.append("```")
|
| 150 |
+
lines.append("")
|
| 151 |
+
|
| 152 |
+
smoking_gun = cluster.get("smoking_gun", [])
|
| 153 |
+
if smoking_gun:
|
| 154 |
+
lines.append("**Smoking-gun error messages:**")
|
| 155 |
+
lines.append("")
|
| 156 |
+
for msg in smoking_gun:
|
| 157 |
+
lines.append(f"- {msg}")
|
| 158 |
+
lines.append("")
|
| 159 |
+
|
| 160 |
+
docs = cluster.get("trace_documents", [])
|
| 161 |
+
if docs:
|
| 162 |
+
lines.append("**Trace documents:**")
|
| 163 |
+
lines.append("")
|
| 164 |
+
headers = ["traceID", "@timestamp"]
|
| 165 |
+
has_action = any("user_action" in d for d in docs)
|
| 166 |
+
if has_action:
|
| 167 |
+
headers.append("user_action")
|
| 168 |
+
rows = []
|
| 169 |
+
for d in docs:
|
| 170 |
+
row = [f"`{d['traceID']}`", d["@timestamp"]]
|
| 171 |
+
if has_action:
|
| 172 |
+
row.append(d.get("user_action", ""))
|
| 173 |
+
rows.append(row)
|
| 174 |
+
lines.append(tabulate(rows, headers=headers, tablefmt="github"))
|
| 175 |
+
lines.append("")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
_LAYER_DESCRIPTIONS = {
|
| 179 |
+
"root_cause": "metric closest to the fault injection point",
|
| 180 |
+
"propagation": "intermediate services reflecting the error through the call chain",
|
| 181 |
+
"symptom": "user-facing impact visible to end users or clients",
|
| 182 |
+
"meta": "feature flag counters or internal plumbing",
|
| 183 |
+
"unknown": "unclassified",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _format_onset(offset: int | None) -> str:
|
| 190 |
+
"""Format an onset offset as '+Xs' or 'N/A'."""
|
| 191 |
+
if offset is None:
|
| 192 |
+
return "N/A"
|
| 193 |
+
return f"+{offset}s"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _format_label_values(labels: dict[str, str]) -> str:
|
| 197 |
+
"""Format label values as a compact comma-separated string."""
|
| 198 |
+
if not labels:
|
| 199 |
+
return ""
|
| 200 |
+
return ", ".join(labels.values())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _earliest_onset(variants: list[dict]) -> int | None:
|
| 204 |
+
"""Return the earliest onset_offset_seconds across variants, or None."""
|
| 205 |
+
offsets = [
|
| 206 |
+
v["onset_offset_seconds"]
|
| 207 |
+
for v in variants
|
| 208 |
+
if v.get("onset_offset_seconds") is not None
|
| 209 |
+
]
|
| 210 |
+
return min(offsets) if offsets else None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None:
|
| 214 |
+
"""Render metric families grouped by signal layer."""
|
| 215 |
+
by_layer: dict[str, list[dict]] = {}
|
| 216 |
+
for fam in metrics_list:
|
| 217 |
+
by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam)
|
| 218 |
+
|
| 219 |
+
for layer in _LAYER_ORDER:
|
| 220 |
+
layer_families = by_layer.get(layer, [])
|
| 221 |
+
if not layer_families:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families]
|
| 225 |
+
layer_onsets = [o for o in layer_onsets if o is not None]
|
| 226 |
+
layer_onset_str = (
|
| 227 |
+
f" (earliest onset: {_format_onset(min(layer_onsets))})"
|
| 228 |
+
if layer_onsets
|
| 229 |
+
else ""
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
display_layer = layer.replace("_", " ").title()
|
| 233 |
+
desc = _LAYER_DESCRIPTIONS.get(layer, "")
|
| 234 |
+
lines.append(f"**{display_layer}** — {desc}{layer_onset_str}")
|
| 235 |
+
lines.append("")
|
| 236 |
+
|
| 237 |
+
for fam in layer_families:
|
| 238 |
+
fam_onset = _earliest_onset(fam["variants"])
|
| 239 |
+
label_vals = _format_label_values(fam.get("defining_labels", {}))
|
| 240 |
+
label_part = f" ({label_vals})" if label_vals else ""
|
| 241 |
+
lines.append(
|
| 242 |
+
f"#### {fam['metric_family']} family{label_part}"
|
| 243 |
+
f" — onset: {_format_onset(fam_onset)}"
|
| 244 |
+
)
|
| 245 |
+
lines.append("")
|
| 246 |
+
|
| 247 |
+
first_desc = (
|
| 248 |
+
fam["variants"][0].get("description", "") if fam["variants"] else ""
|
| 249 |
+
)
|
| 250 |
+
if first_desc:
|
| 251 |
+
lines.append(first_desc)
|
| 252 |
+
lines.append("")
|
| 253 |
+
|
| 254 |
+
for v in fam["variants"]:
|
| 255 |
+
v_onset = _format_onset(v.get("onset_offset_seconds"))
|
| 256 |
+
lines.append(f"- **{v['type']}** (onset: {v_onset})")
|
| 257 |
+
lines.append(f" `{v['query']}`")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None:
|
| 262 |
+
"""Render frontend issues as markdown subsections."""
|
| 263 |
+
for issue in issues:
|
| 264 |
+
route = issue.get("route", "Unknown route")
|
| 265 |
+
lines.append(f"#### {route}")
|
| 266 |
+
lines.append("")
|
| 267 |
+
|
| 268 |
+
description = issue.get("description", "")
|
| 269 |
+
if description:
|
| 270 |
+
lines.append(description)
|
| 271 |
+
lines.append("")
|
| 272 |
+
|
| 273 |
+
rows = [
|
| 274 |
+
["Deterministic", str(issue.get("deterministic", ""))],
|
| 275 |
+
["Trigger condition", issue.get("trigger_condition", "")],
|
| 276 |
+
["Calling service", issue.get("calling_service", "")],
|
| 277 |
+
[
|
| 278 |
+
"Source",
|
| 279 |
+
f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`",
|
| 280 |
+
],
|
| 281 |
+
]
|
| 282 |
+
lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github"))
|
| 283 |
+
lines.append("")
|
| 284 |
+
|
| 285 |
+
call_pattern = issue.get("call_pattern", "")
|
| 286 |
+
if call_pattern:
|
| 287 |
+
lines.append(f"**Call pattern:** {call_pattern}")
|
| 288 |
+
lines.append("")
|
| 289 |
+
|
| 290 |
+
cause = issue.get("cause", "")
|
| 291 |
+
if cause:
|
| 292 |
+
lines.append(f"**Cause:** {cause}")
|
| 293 |
+
lines.append("")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def format_rubric(data: dict, include_frontend: bool = False) -> str:
|
| 297 |
+
"""Convert a rubric JSON dict into a consistently formatted markdown string.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
data: The rubric JSON dict.
|
| 301 |
+
include_frontend: If True, include the ``### Frontend`` section.
|
| 302 |
+
Defaults to False since frontend symptoms may be noisy for
|
| 303 |
+
downstream consumers (LLM judge, oracle solutions).
|
| 304 |
+
TODO(Albert): systematically test the impact of including vs.
|
| 305 |
+
excluding frontend symptoms on downstream consumers.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
lines: list[str] = []
|
| 309 |
+
|
| 310 |
+
lines.append(f"# {data['feature_flag']}")
|
| 311 |
+
lines.append("")
|
| 312 |
+
lines.append(f"**Feature flag:** `{data['feature_flag']}`")
|
| 313 |
+
lines.append("")
|
| 314 |
+
lines.append(f"**Description:** {data['description']}")
|
| 315 |
+
lines.append("")
|
| 316 |
+
lines.append(f"**Incident time:** {data['incident_time']}")
|
| 317 |
+
lines.append("")
|
| 318 |
+
|
| 319 |
+
lines.append("## Mechanism")
|
| 320 |
+
lines.append("")
|
| 321 |
+
lines.append(data["mechanism"])
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
interaction = data.get("interaction", "")
|
| 325 |
+
if interaction:
|
| 326 |
+
lines.append(f"**Interaction with other feature flags:** {interaction}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
|
| 329 |
+
lines.append("## Evidence")
|
| 330 |
+
lines.append("")
|
| 331 |
+
|
| 332 |
+
gs = data["symptoms"]
|
| 333 |
+
|
| 334 |
+
metrics = gs.get("metrics", [])
|
| 335 |
+
lines.append("### Metrics")
|
| 336 |
+
lines.append("")
|
| 337 |
+
if metrics:
|
| 338 |
+
_format_metrics_list(metrics, lines)
|
| 339 |
+
|
| 340 |
+
logs = gs.get("logs", [])
|
| 341 |
+
lines.append("### Logs")
|
| 342 |
+
lines.append("")
|
| 343 |
+
if logs:
|
| 344 |
+
_format_log_clusters(logs, lines)
|
| 345 |
+
|
| 346 |
+
if include_frontend:
|
| 347 |
+
frontend = gs.get("frontend", [])
|
| 348 |
+
lines.append("### Frontend")
|
| 349 |
+
lines.append("")
|
| 350 |
+
if frontend:
|
| 351 |
+
_format_frontend_issues(frontend, lines)
|
| 352 |
+
|
| 353 |
+
traces = gs.get("traces", [])
|
| 354 |
+
lines.append("### Traces")
|
| 355 |
+
lines.append("")
|
| 356 |
+
if traces:
|
| 357 |
+
_format_trace_clusters(traces, lines)
|
| 358 |
+
|
| 359 |
+
return "\n".join(lines)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
# Judge prompt + output-schema builders
|
| 364 |
+
# ---------------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _render_checklist(rubric_data: dict) -> str:
|
| 368 |
+
"""Build per-cluster checklist blocks for metrics/logs/traces."""
|
| 369 |
+
symptoms = rubric_data.get("symptoms", {}) or {}
|
| 370 |
+
metric_clusters = symptoms.get("metrics", []) or []
|
| 371 |
+
log_clusters = symptoms.get("logs", []) or []
|
| 372 |
+
trace_clusters = symptoms.get("traces", []) or []
|
| 373 |
+
|
| 374 |
+
blocks: list[str] = []
|
| 375 |
+
|
| 376 |
+
if metric_clusters:
|
| 377 |
+
lines = ["#### Metric clusters"]
|
| 378 |
+
for i, m in enumerate(metric_clusters):
|
| 379 |
+
family = m.get("metric_family", "")
|
| 380 |
+
lines.append(
|
| 381 |
+
f'- Cluster {i}: `metric_family = "{family}"`'
|
| 382 |
+
f" — family_match: did the agent cite a query targeting"
|
| 383 |
+
f" metric_family `{family}` under a Why-step whose causal chain"
|
| 384 |
+
f" aligns with the rubric?"
|
| 385 |
+
)
|
| 386 |
+
blocks.append("\n".join(lines))
|
| 387 |
+
|
| 388 |
+
if log_clusters:
|
| 389 |
+
lines = ["#### Log clusters"]
|
| 390 |
+
for i, log in enumerate(log_clusters):
|
| 391 |
+
attrs = log.get("representative_attributes") or {}
|
| 392 |
+
body = attrs.get("body", "")
|
| 393 |
+
service_name = attrs.get("resource.service.name", "")
|
| 394 |
+
lines.append(
|
| 395 |
+
f"- Cluster {i}:\n"
|
| 396 |
+
f" - `resource.service.name`: `{service_name}`\n"
|
| 397 |
+
f" - `body`: `{body}`\n"
|
| 398 |
+
f" - body_match: did the agent cite log evidence whose body"
|
| 399 |
+
f" matches the rubric's `body` under a Why-step whose causal"
|
| 400 |
+
f" chain aligns with the rubric?\n"
|
| 401 |
+
f" - service_name_match: did the agent attribute the cited"
|
| 402 |
+
f" log evidence to the OTel service `{service_name}`"
|
| 403 |
+
f" (`resource.service.name`)?"
|
| 404 |
+
)
|
| 405 |
+
blocks.append("\n".join(lines))
|
| 406 |
+
|
| 407 |
+
if trace_clusters:
|
| 408 |
+
lines = ["#### Trace clusters"]
|
| 409 |
+
for i, trace in enumerate(trace_clusters):
|
| 410 |
+
call_chain = trace.get("call_chain", "")
|
| 411 |
+
smoking_gun = trace.get("smoking_gun", []) or []
|
| 412 |
+
sg_rendered = "\n".join(f" - {s}" for s in smoking_gun)
|
| 413 |
+
lines.append(
|
| 414 |
+
f"- Cluster {i}:\n"
|
| 415 |
+
f" - call_chain: `{call_chain}`\n"
|
| 416 |
+
f" - smoking_gun:\n{sg_rendered}\n"
|
| 417 |
+
f" - call_chain_match: did the agent cite evidence matching"
|
| 418 |
+
f" this service-level call chain under a Why-step whose causal"
|
| 419 |
+
f" chain aligns with the rubric?\n"
|
| 420 |
+
f" - smoking_gun_match: did the agent cite at least one of"
|
| 421 |
+
f" the listed smoking-gun signals?"
|
| 422 |
+
)
|
| 423 |
+
blocks.append("\n".join(lines))
|
| 424 |
+
|
| 425 |
+
return (
|
| 426 |
+
"\n\n".join(blocks)
|
| 427 |
+
if blocks
|
| 428 |
+
else "(No metric, log, or trace clusters in rubric.)"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def build_judge_prompt(
|
| 433 |
+
rubrics_data: list[dict],
|
| 434 |
+
predictions: str,
|
| 435 |
+
) -> str:
|
| 436 |
+
"""Render the judge prompt for one or more ground-truth rubrics.
|
| 437 |
+
|
| 438 |
+
The prompt asks the LLM to evaluate the agent's report against **each**
|
| 439 |
+
rubric independently. The agent is credited if it correctly identifies
|
| 440 |
+
any one rubric (the overall score reflects the best match).
|
| 441 |
+
"""
|
| 442 |
+
if not rubrics_data:
|
| 443 |
+
raise ValueError("build_judge_prompt called with no rubrics")
|
| 444 |
+
|
| 445 |
+
rubric_blocks: list[str] = []
|
| 446 |
+
checklist_blocks: list[str] = []
|
| 447 |
+
for i, rubric in enumerate(rubrics_data):
|
| 448 |
+
feature_flag = rubric.get("feature_flag", "")
|
| 449 |
+
rubric_blocks.append(
|
| 450 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 451 |
+
+ format_rubric(rubric)
|
| 452 |
+
)
|
| 453 |
+
checklist_blocks.append(
|
| 454 |
+
f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n"
|
| 455 |
+
+ _render_checklist(rubric)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rubrics_text = "\n\n---\n\n".join(rubric_blocks)
|
| 459 |
+
checklist_text = "\n\n---\n\n".join(checklist_blocks)
|
| 460 |
+
|
| 461 |
+
header = JUDGE_PROMPT_MULTI_HEADER.format(
|
| 462 |
+
rubrics=rubrics_text,
|
| 463 |
+
predictions=predictions,
|
| 464 |
+
)
|
| 465 |
+
return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
_METRIC_ITEM_SCHEMA: dict[str, Any] = {
|
| 469 |
+
"type": "object",
|
| 470 |
+
"properties": {
|
| 471 |
+
"metric_family": {"type": "string"},
|
| 472 |
+
"family_match": {"type": "boolean"},
|
| 473 |
+
},
|
| 474 |
+
"required": ["metric_family", "family_match"],
|
| 475 |
+
"additionalProperties": False,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
_LOG_ITEM_SCHEMA: dict[str, Any] = {
|
| 479 |
+
"type": "object",
|
| 480 |
+
"properties": {
|
| 481 |
+
"body_match": {"type": "boolean"},
|
| 482 |
+
"service_name_match": {"type": "boolean"},
|
| 483 |
+
},
|
| 484 |
+
"required": ["body_match", "service_name_match"],
|
| 485 |
+
"additionalProperties": False,
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
_TRACE_ITEM_SCHEMA: dict[str, Any] = {
|
| 489 |
+
"type": "object",
|
| 490 |
+
"properties": {
|
| 491 |
+
"call_chain_match": {"type": "boolean"},
|
| 492 |
+
"smoking_gun_match": {"type": "boolean"},
|
| 493 |
+
},
|
| 494 |
+
"required": ["call_chain_match", "smoking_gun_match"],
|
| 495 |
+
"additionalProperties": False,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
_PER_RUBRIC_SCHEMA: dict[str, Any] = {
|
| 500 |
+
"type": "object",
|
| 501 |
+
"properties": {
|
| 502 |
+
"feature_flag": {"type": "string"},
|
| 503 |
+
"incident_time_within_10min": {"type": "boolean"},
|
| 504 |
+
"feature_flag_match": {"type": "boolean"},
|
| 505 |
+
"mechanism_match": {"type": "boolean"},
|
| 506 |
+
"symptoms": {
|
| 507 |
+
"type": "object",
|
| 508 |
+
"properties": {
|
| 509 |
+
"metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA},
|
| 510 |
+
"logs": {"type": "array", "items": _LOG_ITEM_SCHEMA},
|
| 511 |
+
"traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA},
|
| 512 |
+
},
|
| 513 |
+
"required": ["metrics", "logs", "traces"],
|
| 514 |
+
"additionalProperties": False,
|
| 515 |
+
},
|
| 516 |
+
},
|
| 517 |
+
"required": [
|
| 518 |
+
"feature_flag",
|
| 519 |
+
"incident_time_within_10min",
|
| 520 |
+
"feature_flag_match",
|
| 521 |
+
"mechanism_match",
|
| 522 |
+
"symptoms",
|
| 523 |
+
],
|
| 524 |
+
"additionalProperties": False,
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def build_judge_output_schema(rubrics_data: list[dict]) -> dict:
|
| 529 |
+
"""Build a strict JSON Schema for the judge output: one verdict per rubric
|
| 530 |
+
+ an overall ``score`` integer. Falls back to a minimal ``{score: int}``
|
| 531 |
+
schema when no rubrics are supplied (no-incident path).
|
| 532 |
+
|
| 533 |
+
Per-rubric cluster-array lengths vary across rubrics; rather than encode
|
| 534 |
+
a per-element schema (which Structured Outputs doesn't support), we leave
|
| 535 |
+
the array lengths unconstrained and rely on the prompt instructions to
|
| 536 |
+
keep cluster order matching.
|
| 537 |
+
"""
|
| 538 |
+
if not rubrics_data:
|
| 539 |
+
return {
|
| 540 |
+
"type": "object",
|
| 541 |
+
"properties": {"score": {"type": "integer"}},
|
| 542 |
+
"required": ["score"],
|
| 543 |
+
"additionalProperties": False,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
n = len(rubrics_data)
|
| 547 |
+
return {
|
| 548 |
+
"type": "object",
|
| 549 |
+
"properties": {
|
| 550 |
+
"rubrics": {
|
| 551 |
+
"type": "array",
|
| 552 |
+
"minItems": n,
|
| 553 |
+
"maxItems": n,
|
| 554 |
+
"items": _PER_RUBRIC_SCHEMA,
|
| 555 |
+
},
|
| 556 |
+
"score": {"type": "integer"},
|
| 557 |
+
},
|
| 558 |
+
"required": ["rubrics", "score"],
|
| 559 |
+
"additionalProperties": False,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# ---------------------------------------------------------------------------
|
| 564 |
+
# API call
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
async def async_call_llm_judge(
|
| 569 |
+
client: Any,
|
| 570 |
+
prompt: str,
|
| 571 |
+
model: str = DEFAULT_MODEL,
|
| 572 |
+
reasoning_effort: str | None = None,
|
| 573 |
+
output_schema: dict | None = None,
|
| 574 |
+
) -> tuple[str, list[dict] | None]:
|
| 575 |
+
"""Call the LLM judge via the OpenAI Responses API (falling back to Chat).
|
| 576 |
+
|
| 577 |
+
When ``output_schema`` is provided, uses Structured Outputs (strict JSON
|
| 578 |
+
Schema) so the returned text is guaranteed to conform to the schema.
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
A tuple of (output_text, reasoning_summaries). reasoning_summaries is
|
| 582 |
+
None when reasoning_effort is not set.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
text_format: dict[str, Any] = (
|
| 586 |
+
{
|
| 587 |
+
"type": "json_schema",
|
| 588 |
+
"name": "judge_response",
|
| 589 |
+
"schema": output_schema,
|
| 590 |
+
"strict": True,
|
| 591 |
+
}
|
| 592 |
+
if output_schema is not None
|
| 593 |
+
else {"type": "text"}
|
| 594 |
+
)
|
| 595 |
+
try:
|
| 596 |
+
kwargs: dict[str, Any] = {
|
| 597 |
+
"model": model,
|
| 598 |
+
"input": prompt,
|
| 599 |
+
"text": {"format": text_format},
|
| 600 |
+
"tools": [],
|
| 601 |
+
"store": True,
|
| 602 |
+
"max_output_tokens": 16384,
|
| 603 |
+
}
|
| 604 |
+
if reasoning_effort is not None:
|
| 605 |
+
kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
| 606 |
+
response = await client.responses.create(**kwargs)
|
| 607 |
+
reasoning_summaries = None
|
| 608 |
+
if reasoning_effort is not None:
|
| 609 |
+
reasoning_summaries = [
|
| 610 |
+
[
|
| 611 |
+
s.model_dump() if hasattr(s, "model_dump") else s
|
| 612 |
+
for s in item.summary
|
| 613 |
+
]
|
| 614 |
+
for item in response.output
|
| 615 |
+
if getattr(item, "type", None) == "reasoning"
|
| 616 |
+
and getattr(item, "summary", None) is not None
|
| 617 |
+
]
|
| 618 |
+
return response.output_text, reasoning_summaries
|
| 619 |
+
except Exception as exc:
|
| 620 |
+
if "404" not in str(exc):
|
| 621 |
+
raise
|
| 622 |
+
logger.info(
|
| 623 |
+
f"Responses API returned 404 for {model}, falling back to Chat Completions"
|
| 624 |
+
)
|
| 625 |
+
chat_kwargs: dict[str, Any] = {
|
| 626 |
+
"model": model,
|
| 627 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 628 |
+
"max_tokens": 16384,
|
| 629 |
+
}
|
| 630 |
+
if output_schema is not None:
|
| 631 |
+
chat_kwargs["response_format"] = {
|
| 632 |
+
"type": "json_schema",
|
| 633 |
+
"json_schema": {
|
| 634 |
+
"name": "judge_response",
|
| 635 |
+
"schema": output_schema,
|
| 636 |
+
"strict": True,
|
| 637 |
+
},
|
| 638 |
+
}
|
| 639 |
+
if reasoning_effort is not None:
|
| 640 |
+
chat_kwargs["reasoning_effort"] = reasoning_effort
|
| 641 |
+
response = await client.chat.completions.create(**chat_kwargs)
|
| 642 |
+
reasoning_summaries = None
|
| 643 |
+
if reasoning_effort is not None:
|
| 644 |
+
reasoning_content = getattr(
|
| 645 |
+
response.choices[0].message, "reasoning_content", None
|
| 646 |
+
)
|
| 647 |
+
if reasoning_content is not None:
|
| 648 |
+
reasoning_summaries = [{"type": "text", "text": reasoning_content}]
|
| 649 |
+
else:
|
| 650 |
+
reasoning_summaries = []
|
| 651 |
+
return response.choices[0].message.content, reasoning_summaries
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# ---------------------------------------------------------------------------
|
| 655 |
+
# Parsing + aggregation
|
| 656 |
+
# ---------------------------------------------------------------------------
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def parse_judge_response(response_text: str) -> dict:
|
| 660 |
+
"""Parse the judge response JSON and range-check ``score``.
|
| 661 |
+
|
| 662 |
+
When Structured Outputs are used upstream, the response is already
|
| 663 |
+
schema-validated; this function only decodes the JSON and enforces the
|
| 664 |
+
0-3 range for ``score``.
|
| 665 |
+
"""
|
| 666 |
+
parsed = json.loads(response_text)
|
| 667 |
+
score = int(parsed["score"])
|
| 668 |
+
if score < 0 or score > 3:
|
| 669 |
+
raise ValueError(f"Score {score} out of range [0, 3]")
|
| 670 |
+
parsed["score"] = score
|
| 671 |
+
return parsed
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _aggregate_one_rubric(verdict: dict) -> dict:
|
| 675 |
+
"""Roll up cluster verdicts for a single per-rubric judge entry."""
|
| 676 |
+
symptoms = verdict.get("symptoms", {}) or {}
|
| 677 |
+
metrics = symptoms.get("metrics", []) or []
|
| 678 |
+
logs = symptoms.get("logs", []) or []
|
| 679 |
+
traces = symptoms.get("traces", []) or []
|
| 680 |
+
|
| 681 |
+
metric_hits = [bool(m.get("family_match")) for m in metrics]
|
| 682 |
+
log_hits = [
|
| 683 |
+
bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs
|
| 684 |
+
]
|
| 685 |
+
trace_hits = [
|
| 686 |
+
bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match"))
|
| 687 |
+
for t in traces
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
def _all(hits: list[bool]) -> bool | None:
|
| 691 |
+
return all(hits) if hits else None
|
| 692 |
+
|
| 693 |
+
def _any(hits: list[bool]) -> bool | None:
|
| 694 |
+
return any(hits) if hits else None
|
| 695 |
+
|
| 696 |
+
return {
|
| 697 |
+
"feature_flag": verdict.get("feature_flag", ""),
|
| 698 |
+
"incident_time_within_10min": bool(verdict.get("incident_time_within_10min")),
|
| 699 |
+
"feature_flag_match": bool(verdict.get("feature_flag_match")),
|
| 700 |
+
"mechanism_match": bool(verdict.get("mechanism_match")),
|
| 701 |
+
"metrics_all_match": _all(metric_hits),
|
| 702 |
+
"metrics_any_match": _any(metric_hits),
|
| 703 |
+
"logs_all_match": _all(log_hits),
|
| 704 |
+
"logs_any_match": _any(log_hits),
|
| 705 |
+
"traces_all_match": _all(trace_hits),
|
| 706 |
+
"traces_any_match": _any(trace_hits),
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def aggregate_judge_response(parsed: dict) -> dict:
|
| 711 |
+
"""Aggregate per-rubric, per-cluster verdicts into flat any-of rollups.
|
| 712 |
+
|
| 713 |
+
The agent is credited if it matches any one of the listed rubrics.
|
| 714 |
+
Per-rubric rollups are computed via ``_aggregate_one_rubric``; the
|
| 715 |
+
task-level rollup is the ``any`` over rubrics for booleans (with ``None``
|
| 716 |
+
skipped — sections without clusters in any rubric stay ``None``).
|
| 717 |
+
|
| 718 |
+
The per-rubric rollups are also returned under ``per_rubric`` for
|
| 719 |
+
downstream analysis that needs to know which specific rubric matched.
|
| 720 |
+
"""
|
| 721 |
+
rubrics = parsed.get("rubrics") or []
|
| 722 |
+
per_rubric = [_aggregate_one_rubric(r) for r in rubrics]
|
| 723 |
+
|
| 724 |
+
def _any_skip_none(values: list[bool | None]) -> bool | None:
|
| 725 |
+
truthy = [v for v in values if v is not None]
|
| 726 |
+
return any(truthy) if truthy else None
|
| 727 |
+
|
| 728 |
+
return {
|
| 729 |
+
"incident_time_within_10min": _any_skip_none(
|
| 730 |
+
[r["incident_time_within_10min"] for r in per_rubric]
|
| 731 |
+
)
|
| 732 |
+
or False,
|
| 733 |
+
"feature_flag_match": _any_skip_none(
|
| 734 |
+
[r["feature_flag_match"] for r in per_rubric]
|
| 735 |
+
)
|
| 736 |
+
or False,
|
| 737 |
+
"mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric])
|
| 738 |
+
or False,
|
| 739 |
+
"metrics_all_match": _any_skip_none(
|
| 740 |
+
[r["metrics_all_match"] for r in per_rubric]
|
| 741 |
+
),
|
| 742 |
+
"metrics_any_match": _any_skip_none(
|
| 743 |
+
[r["metrics_any_match"] for r in per_rubric]
|
| 744 |
+
),
|
| 745 |
+
"logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]),
|
| 746 |
+
"logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]),
|
| 747 |
+
"traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]),
|
| 748 |
+
"traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]),
|
| 749 |
+
"per_rubric": per_rubric,
|
| 750 |
+
"score": int(parsed["score"]),
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def string_match_fallback(expected: dict, predictions: str) -> dict:
|
| 755 |
+
"""Fall back to case-insensitive string search for any plausible root_cause.
|
| 756 |
+
|
| 757 |
+
``expected["events"]`` is a list of ``{"root_cause": <flag>, "event_time": ...}``;
|
| 758 |
+
the agent's report is credited if any listed root_cause appears in it.
|
| 759 |
+
Returns a result dict compatible with the judge output format.
|
| 760 |
+
"""
|
| 761 |
+
events: list[dict] = expected.get("events") or []
|
| 762 |
+
if not events:
|
| 763 |
+
# No-incident task: agent should write an empty report.
|
| 764 |
+
return {"score": 3 if len(predictions.strip()) == 0 else 0}
|
| 765 |
+
text = predictions.lower()
|
| 766 |
+
found = any(e["root_cause"].strip().lower() in text for e in events)
|
| 767 |
+
return {"score": 3 if found else 0}
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# ---------------------------------------------------------------------------
|
| 771 |
+
# Judge entry point (used by both modes)
|
| 772 |
+
# ---------------------------------------------------------------------------
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
async def judge(
|
| 776 |
+
client: Any,
|
| 777 |
+
expected: dict,
|
| 778 |
+
predictions: str,
|
| 779 |
+
rubrics_data: list[dict],
|
| 780 |
+
model: str = DEFAULT_MODEL,
|
| 781 |
+
reasoning_effort: str | None = None,
|
| 782 |
+
) -> dict:
|
| 783 |
+
"""Run the LLM judge over one or more ground-truth rubrics, or
|
| 784 |
+
short-circuit for no-incident tasks.
|
| 785 |
+
|
| 786 |
+
Returns:
|
| 787 |
+
A dict with keys: reward, mode, score, and (for LLM judge) model,
|
| 788 |
+
nested (raw judge response), reasoning_summary, rubric_used,
|
| 789 |
+
judge_prompt, judge_response_raw. Per-section rollups are derived
|
| 790 |
+
post-hoc from ``nested`` by formatters via ``aggregate_judge_response``.
|
| 791 |
+
|
| 792 |
+
"""
|
| 793 |
+
events: list[dict] = expected.get("events") or []
|
| 794 |
+
if not events:
|
| 795 |
+
score = 3 if len(predictions.strip()) == 0 else 0
|
| 796 |
+
return {
|
| 797 |
+
"reward": score / 3.0,
|
| 798 |
+
"mode": "no_incident",
|
| 799 |
+
"model": model,
|
| 800 |
+
"score": score,
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
# Short-circuit when the agent emitted an empty report despite an incident.
|
| 804 |
+
# No LLM call can rescue this; score is a guaranteed 0. We synthesize the
|
| 805 |
+
# nested response shape (per-rubric all False, matching cluster counts)
|
| 806 |
+
# so that ``aggregate_judge_response`` produces the expected all-False
|
| 807 |
+
# rollups at load time.
|
| 808 |
+
if not predictions.strip():
|
| 809 |
+
synthetic_per_rubric = []
|
| 810 |
+
for rubric in rubrics_data:
|
| 811 |
+
symptoms = rubric.get("symptoms", {}) or {}
|
| 812 |
+
synthetic_per_rubric.append(
|
| 813 |
+
{
|
| 814 |
+
"feature_flag": rubric.get("feature_flag", ""),
|
| 815 |
+
"incident_time_within_10min": False,
|
| 816 |
+
"feature_flag_match": False,
|
| 817 |
+
"mechanism_match": False,
|
| 818 |
+
"symptoms": {
|
| 819 |
+
"metrics": [
|
| 820 |
+
{
|
| 821 |
+
"metric_family": m.get("metric_family", ""),
|
| 822 |
+
"family_match": False,
|
| 823 |
+
}
|
| 824 |
+
for m in (symptoms.get("metrics") or [])
|
| 825 |
+
],
|
| 826 |
+
"logs": [
|
| 827 |
+
{"body_match": False, "service_name_match": False}
|
| 828 |
+
for _ in (symptoms.get("logs") or [])
|
| 829 |
+
],
|
| 830 |
+
"traces": [
|
| 831 |
+
{"call_chain_match": False, "smoking_gun_match": False}
|
| 832 |
+
for _ in (symptoms.get("traces") or [])
|
| 833 |
+
],
|
| 834 |
+
},
|
| 835 |
+
}
|
| 836 |
+
)
|
| 837 |
+
return {
|
| 838 |
+
"mode": "empty_report",
|
| 839 |
+
"model": model,
|
| 840 |
+
"score": 0,
|
| 841 |
+
"reward": 0.0,
|
| 842 |
+
"rubric_used": bool(rubrics_data),
|
| 843 |
+
"nested": {"rubrics": synthetic_per_rubric, "score": 0},
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
prompt = build_judge_prompt(rubrics_data, predictions)
|
| 847 |
+
output_schema = build_judge_output_schema(rubrics_data)
|
| 848 |
+
|
| 849 |
+
raw_response, reasoning_summary = await async_call_llm_judge(
|
| 850 |
+
client,
|
| 851 |
+
prompt,
|
| 852 |
+
model=model,
|
| 853 |
+
reasoning_effort=reasoning_effort,
|
| 854 |
+
output_schema=output_schema,
|
| 855 |
+
)
|
| 856 |
+
parsed = parse_judge_response(raw_response)
|
| 857 |
+
|
| 858 |
+
# Per-section rollups are NOT spread into the result — they're a pure
|
| 859 |
+
# post-hoc derivation from ``nested`` via ``aggregate_judge_response``,
|
| 860 |
+
# applied by the formatters at load time so schema changes don't require
|
| 861 |
+
# rewriting saved JSONs.
|
| 862 |
+
return {
|
| 863 |
+
"mode": "llm_judge",
|
| 864 |
+
"model": model,
|
| 865 |
+
"score": parsed["score"],
|
| 866 |
+
"reward": parsed["score"] / 3.0,
|
| 867 |
+
"reasoning_summary": reasoning_summary,
|
| 868 |
+
"rubric_used": bool(rubrics_data),
|
| 869 |
+
"judge_prompt": prompt,
|
| 870 |
+
"judge_response_raw": raw_response,
|
| 871 |
+
"nested": parsed,
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# CLI
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
async def main() -> None:
|
| 881 |
+
"""Entry point: load expected + predictions, score, write reward/details."""
|
| 882 |
+
parser = argparse.ArgumentParser(
|
| 883 |
+
description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks."
|
| 884 |
+
)
|
| 885 |
+
parser.add_argument("--expected", type=str, default="/tests/expected.json")
|
| 886 |
+
parser.add_argument("--predictions", type=str, default="/app/report.md")
|
| 887 |
+
parser.add_argument(
|
| 888 |
+
"--rubrics-dir",
|
| 889 |
+
type=str,
|
| 890 |
+
default="/tests/rubrics",
|
| 891 |
+
help=(
|
| 892 |
+
"Directory containing one rubric JSON per plausible root cause "
|
| 893 |
+
"(e.g. /tests/rubrics/<event_id>.json). The judge scores the "
|
| 894 |
+
"agent against any one of them."
|
| 895 |
+
),
|
| 896 |
+
)
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name."
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"--effort",
|
| 902 |
+
type=str,
|
| 903 |
+
choices=["low", "medium", "high"],
|
| 904 |
+
default="high",
|
| 905 |
+
help="Reasoning effort level for the judge LLM (default: high).",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"--mode",
|
| 909 |
+
type=str,
|
| 910 |
+
choices=["string_match", "llm_judge"],
|
| 911 |
+
default="string_match",
|
| 912 |
+
help="Scoring mode: string_match or llm_judge (default: string_match).",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt")
|
| 915 |
+
parser.add_argument("--details", type=str, default="/logs/verifier/details.json")
|
| 916 |
+
args = parser.parse_args()
|
| 917 |
+
|
| 918 |
+
expected_path = Path(args.expected)
|
| 919 |
+
predictions_path = Path(args.predictions)
|
| 920 |
+
rubrics_dir = Path(args.rubrics_dir)
|
| 921 |
+
reward_path = Path(args.reward)
|
| 922 |
+
details_path = Path(args.details)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
# Load expected
|
| 926 |
+
print(f"Loading expected results from {expected_path}...")
|
| 927 |
+
with expected_path.open() as f:
|
| 928 |
+
expected = json.load(f)
|
| 929 |
+
|
| 930 |
+
# Load predictions (markdown report)
|
| 931 |
+
print(f"Loading predictions from {predictions_path}...")
|
| 932 |
+
predictions = predictions_path.read_text()
|
| 933 |
+
|
| 934 |
+
# Load rubric JSONs — one per plausible root cause. Order is the
|
| 935 |
+
# filesystem sort order, which matches the build_harbor_tasks.py
|
| 936 |
+
# naming convention (event_id stems sort lexicographically).
|
| 937 |
+
rubrics_data: list[dict] = []
|
| 938 |
+
if expected.get("events"):
|
| 939 |
+
if rubrics_dir.is_dir():
|
| 940 |
+
rubric_paths = sorted(rubrics_dir.glob("*.json"))
|
| 941 |
+
for p in rubric_paths:
|
| 942 |
+
with p.open() as f:
|
| 943 |
+
rubrics_data.append(json.load(f))
|
| 944 |
+
print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}")
|
| 945 |
+
else:
|
| 946 |
+
print(f"Rubric directory missing: {rubrics_dir}")
|
| 947 |
+
else:
|
| 948 |
+
print("No incident events in expected results; skipping rubric load.")
|
| 949 |
+
|
| 950 |
+
# Run judge
|
| 951 |
+
if args.mode == "string_match":
|
| 952 |
+
em = string_match_fallback(expected, predictions)
|
| 953 |
+
result = {"reward": em["score"] / 3.0, "mode": "string_match", **em}
|
| 954 |
+
else:
|
| 955 |
+
from openai import AsyncOpenAI
|
| 956 |
+
|
| 957 |
+
client = AsyncOpenAI(
|
| 958 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 959 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 960 |
+
)
|
| 961 |
+
result = await judge(
|
| 962 |
+
client,
|
| 963 |
+
expected,
|
| 964 |
+
predictions,
|
| 965 |
+
rubrics_data,
|
| 966 |
+
model=args.model,
|
| 967 |
+
reasoning_effort=args.effort,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Write reward
|
| 971 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 972 |
+
reward_path.write_text(str(result["reward"]))
|
| 973 |
+
|
| 974 |
+
# Write details
|
| 975 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 976 |
+
details_path.write_text(json.dumps(result, indent=2))
|
| 977 |
+
|
| 978 |
+
print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})")
|
| 979 |
+
print(f"Mode: {result['mode']}")
|
| 980 |
+
if result.get("reasoning_summary"):
|
| 981 |
+
print(f"Reasoning summary: {result['reasoning_summary']}")
|
| 982 |
+
|
| 983 |
+
if result["reward"] < 1.0:
|
| 984 |
+
sys.exit(1)
|
| 985 |
+
|
| 986 |
+
except Exception as exc:
|
| 987 |
+
reward_path.parent.mkdir(parents=True, exist_ok=True)
|
| 988 |
+
reward_path.write_text("0.0")
|
| 989 |
+
details_path.parent.mkdir(parents=True, exist_ok=True)
|
| 990 |
+
details_path.write_text(
|
| 991 |
+
json.dumps(
|
| 992 |
+
{
|
| 993 |
+
"reward": 0.0,
|
| 994 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 995 |
+
"traceback": traceback.format_exc(),
|
| 996 |
+
},
|
| 997 |
+
indent=2,
|
| 998 |
+
)
|
| 999 |
+
)
|
| 1000 |
+
print(f"Verifier error: {type(exc).__name__}: {exc}")
|
| 1001 |
+
sys.exit(1)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
if __name__ == "__main__":
|
| 1005 |
+
asyncio.run(main())
|
tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"incident_time": "2026-04-19T14:01:51.404464+00:00",
|
| 3 |
+
"feature_flag": "imageSlowLoad",
|
| 4 |
+
"description": "A feature flag in the frontend `ProductCard` React component added an `x-envoy-fault-delay-request` header (plus `Cache-Control: no-cache`) to every product-image fetch; Envoy honored the fault-injection header and artificially delayed each `GET /images/products/<picture>` response, so product thumbnails took seconds to render.",
|
| 5 |
+
"mechanism": "The flag is read in [`ProductCard.tsx#L32`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L32): the `ProductCard` React component calls `useNumberFlagValue('imageSlowLoad', 0)` to get the delay value in milliseconds (variants: `0` for off, `5000` for 5 sec, `10000` for 10 sec). When non-zero, the component sets the `x-envoy-fault-delay-request` header to the flag value on every product image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)).\n\nThe image request is sent to `/images/products/<picture>`, which the frontend-proxy Envoy routes to the `image-provider` cluster ([`envoy.tmpl.yaml#L54-L55`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L54)). Envoy's `envoy.filters.http.fault` filter is configured with `header_delay: {}` and 100% percentage ([`envoy.tmpl.yaml#L67-L74`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)), meaning it honors the `x-envoy-fault-delay-request` header and injects the specified delay (in ms) before forwarding the request. Every product card image load is therefore delayed by the flag value (e.g. 5 or 10 seconds), causing the page to render with blank/loading images until the delayed responses arrive.",
|
| 6 |
+
"symptoms": {
|
| 7 |
+
"metrics": [],
|
| 8 |
+
"logs": [],
|
| 9 |
+
"frontend": [
|
| 10 |
+
{
|
| 11 |
+
"description": "Product card thumbnails on the homepage product grid (and the recommendations carousel on product/cart/checkout pages) render with a blank image placeholder for ~5 seconds before the actual thumbnail appears. The page text and layout render immediately; only the images are delayed. Affects every product card on every page load while the flag is on — the failure is silent slowness, not a visible error.",
|
| 12 |
+
"route": "GET /images/products/<picture>",
|
| 13 |
+
"deterministic": true,
|
| 14 |
+
"trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/<id>`), cart, and checkout pages.",
|
| 15 |
+
"source_file": "src/frontend/components/ProductCard/ProductCard.tsx",
|
| 16 |
+
"source_line": 37,
|
| 17 |
+
"calling_service": "frontend",
|
| 18 |
+
"call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/<picture>`) with header `x-envoy-fault-delay-request: 5000` ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)) → frontend-proxy Envoy → image-provider.",
|
| 19 |
+
"cause": "`useNumberFlagValue('imageSlowLoad', 0)` returns 5000 (the `5sec` variant value, [`demo.flagd.json` `imageSlowLoad.variants.5sec`](../../opentelemetry-demo/src/flagd/demo.flagd.json)). ProductCard sets `x-envoy-fault-delay-request: 5000` on every image fetch ([`ProductCard.tsx#L37`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L37)). The frontend-proxy `envoy.filters.http.fault` filter ([`envoy.tmpl.yaml#L67`](../../opentelemetry-demo/src/frontend-proxy/envoy.tmpl.yaml#L67)) honors this header and delays each image response by 5000ms before forwarding to image-provider, so each `<S.Image>` only resolves after that delay."
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"traces": []
|
| 23 |
+
}
|
| 24 |
+
}
|